使用 WooCommerce 中的挂钩更新产品价格

2024-04-04

我正在尝试使用元键更新产品正常价格_regular_price当产品在 wp-admin 中更新时,使用整数或字符串。

我想要的用户流程是:

  1. 打开产品编辑页面
  2. 单击更新按钮
  3. 页面重新加载后,请看到 _regular_price 设置为 20。

add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
    update_post_meta( $post_id, '_regular_price', 20 );
}

请帮助我找到我在上述函数中做错了什么,并让我知道完成此操作的任何其他方法。


Updated (2018年8月)

您的代码是正确的,但该挂钩是为 Metaboxes 自定义字段制作的。

你应该使用save_post_{$post->post_type} https://developer.wordpress.org/reference/hooks/save_post_post-post_type/WordPress 钩子仅定位产品帖子类型.

此外,您可能需要更新有效价格和刷新产品临时缓存与功能wc_delete_product_transients() https://docs.woocommerce.com/wc-apidocs/source-function-wc_delete_product_transients.html#135-181.

所以你的代码将是:

add_action( 'save_post', 'update_the_product_price', 10, 3 );
function update_the_product_price( $post_id, $post, $update ) {

    if ( $post->post_type != 'product') return; // Only products
    
    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user's permissions.
    if ( ! current_user_can( 'edit_product', $post_id ) )
        return $post_id;

    $price = 50; // <===  <===  <===  <===  <===  <=== Set your price

    $product = wc_get_product( $post_id ); // The WC_Product object

    // if product is not on sale
    if( ! $product->is_on_sale() ){
        update_post_meta( $post_id, '_price', $price ); // Update active price
    }
    update_post_meta( $post_id, '_regular_price', $price ); // Update regular price
    wc_delete_product_transients( $post_id ); // Update product cache
}

代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。

经过测试并有效...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 WooCommerce 中的挂钩更新产品价格 的相关文章

随机推荐