Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Woocommerce从外部来源更新价格_Php_Wordpress_Woocommerce_Hook Woocommerce - Fatal编程技术网

Php Woocommerce从外部来源更新价格

Php Woocommerce从外部来源更新价格,php,wordpress,woocommerce,hook-woocommerce,Php,Wordpress,Woocommerce,Hook Woocommerce,我对从外部数据库更新产品价格有问题。我需要检查每个进入这个职位的产品的价格。为此,我使用了_post挂钩。例如,我得到了单个产品的“1718”价格值 function chd_the_post_action( $post ) { if ( $post && $post->post_type == 'product' ) { $product = wc_get_product( $post->ID ); if ( $produ

我对从外部数据库更新产品价格有问题。我需要检查每个进入这个职位的产品的价格。为此,我使用了_post挂钩。例如,我得到了单个产品的“1718”价格值

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();
        }
    }
}
此代码更新数据库中的产品价格,但不会同时更改页面上的价格视图,而是仅在重新加载页面后更改,因为post和产品变量是由setup_postdata()设置的。 因此,我使用woocommerce挂钩显示更新的价格:

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 );

有什么钩子可以让我以更好的方式执行此操作吗?

使用如下的Update\u post\u元函数更新产品价格

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

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

对$product->set_price($price)的命令相同;而且,只有在重新加载页面后,才不会立即导致页面上的价格值发生变化。尽管如此,这可能会起作用,但最好不要直接更新数据库。通常,您应该使用API$product->set_XXX(),因为根据字段的不同,Woocommerce将执行一些一致性检查,并自动相应地更新相关字段。实际上,这将不起作用,因为根据“\u销售价格”和“\u常规价格”计算的字段“\u价格”将不会更新。但是,如果您使用该API,WooCommerce将自动重新计算“\u price”并将其保存到表“wp\u postETA”中。对于chd\u the\u post\u action(),请尝试操作“post\u submitbox\u misc\u actions”。执行$product->set\u price()也不正确由于WooCommerce将使用sale from/to日期从常规价格和销售价格自动计算价格。它将忽略您在此处设置的任何内容。@user8262086 post_submitbox_misc_actions actions action action action action action action action action action action action action action action action action action action action action action action action action action action Act。当有人访问带有productTry add_action的页面时,我需要更新价格('the_post','chd_the_post_action',9);9所以您首先运行。或者,在chd\u中放入一个全局$product the\u post\u action(),因为您的代码只会真正更新数据库,但先前从原始数据库创建的全局$product保持不变。global将防止global$产品过时。