Woocommerce Update Price from an External Source

I have a problem updating the product price from an external database. I need to check the price of the product every time I access this item. For this I use the_post . For example, I received the cost "1718" for one 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 updates the price of the product in the database, but does not change the form of the price on the page at the same time, but only after reloading the page, since the post and product parameters were set using setup_postdata () . Therefore, I use a woocommerce hook to display the 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 make this action better?

+4
2

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

0

, update_post_meta,

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

Source: https://habr.com/ru/post/1683498/


All Articles