Rosalito Udtohan
Rosalito Udtohan

Reputation: 197

Update woocommerce price of a product based on php

I have a custom add to cart button in php for a single product:

Final total<br>
            $<?php echo $row['purchase-price'] ?>.00<br><br>
            <button onclick="window.location.href='https://yourdomain.com/checkout/?add-to-cart=362166';">Add to cart</button>

After clicking the button, it returned a "Sorry, this product cannot be purchased." error. I havent set the product price since the amount in <?php echo $row['purchase-price'] ?> is always changing. How to pass the amount set in php and pass it to product's final price?

Upvotes: 0

Views: 365

Answers (1)

rajat.gite
rajat.gite

Reputation: 446

  1. First you will restrict your code to single product and archives pages only:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );

function double_price( $price, $product ){
    if( is_shop() || is_product_category() || is_product_tag() || is_product() ) {
        global $wpdb;
        //your query to get price from custom db
        //FOR GET PRODUCT ID $product->get_id();
        $price = $row['purchase-price'];
    }
    return $price;
}
  1. Then for cart and checkout pages, you will change the cart item price this way:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
    global $wpdb;
    //your query to get price from custom db
    $new_price = $row['purchase-price'];

    //FOR GET PRODUCT ID $cart_item['data']->get_id();

    // Set and register the new calculated price
    $cart_data['data']->set_price( $new_price );
    $cart_data['new_price'] = $new_price;

    return $cart_data;
}

add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
    if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
        return $session_data;

    // Get the new calculated price and update cart session item price
    $session_data['data']->set_price( $session_data['new_price'] );

    return $session_data;
}

And in the last hit your custom url

<button onclick="window.location.href='https://yourdomain.com/?add-to-cart=362166&quantity=1';">Add to cart</button>

Upvotes: 1

Related Questions