Home » Wordpress » Woocommerce update price from external source

Woocommerce update price from external source

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have issue with updating of product price from external database. I need to check price of product in every access to this position. For that I use the_post hook. For example I got ‘1718’ price value for single product.

function chd_the_post_action( $post ) {
    if ( $post && $post->post_type == 'product' ) {
        $product = wc_get_product( $post->ID );  
        if ( $product ) {
            $price = '1718';
            $product->set_price( "$price" );    
            $product->set_regular_price( "$price" );    
            $product->set_sale_price( "$price" );    
            $product->save();
        }
    }
}

This code update product price in database, but it’s not change view of price on page in the same moment, but only after page reload because post and product variables was setup by setup_postdata().
Therefore I use woocommerce hook for display updated price:

function chd_get_price_filter( $price, $item ) {
    return '1718';
}
add_filter( 'woocommerce_product_get_price', 'chd_get_price_filter', 100, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'chd_get_price_filter', 100, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'chd_get_price_filter', 100, 2 );

Is there any hook in which I can do this action in better way?

Answers:

Update product price using update_post_meta function like this

update_post_meta( $product->id, '_sale_price', '1718' );
update_post_meta( $product->id, '_regular_price', '1718 );

Questions:
Answers:

add_action( 'the_post', 'chd_the_post_action', 9, 1);