【问题标题】:Update product price using a hook in Woocommerce在 Woocommerce 中使用挂钩更新产品价格
【发布时间】:2018-04-26 22:08:50
【问题描述】:

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

我想要的用户流程是:

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

请帮我找出我在上述功能中做错了什么,并告诉我任何其他方法来完成此操作。

【问题讨论】:

    标签: php wordpress woocommerce product price


    【解决方案1】:

    更新 (2018 年 8 月)

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

    您应该改用 save_post_{$post->post_type} Wordpress hook 仅定位产品帖子类型

    您可能还需要更新有效价格并刷新产品瞬态缓存,使用函数wc_delete_product_transients()

    所以你的代码将是:

    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 文件或任何插件文件中。

    经过测试并且可以工作……

    【讨论】:

    • 这太完美了!
    【解决方案2】:

    要处理 woocommerce_process_product_meta,我猜您缺少参数。我希望下面的代码可以满足您的需要。

    add_action( 'woocommerce_process_product_meta',  $wc_meta_box_product_data_save,  $int,  $int ); 
    

    参数(3)

    • $wc_meta_box_product_data_save(字符串)=> 'WC_Meta_Box_Product_Data::save' wc 元框产品数据保存。
    • $int (int) => 10 整数。
    • $int (int) => 2 整数。

    您可以找到详细信息in this link

    【讨论】:

    • 我将10, 2 添加为整数,但它没有创建所需的结果。其他东西,比如_stock 和我所有的自定义元数据,都可以用我上面的函数更新。只有_regular_price 会导致问题。
    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 2012-08-19
    • 2018-12-06
    • 1970-01-01
    • 2020-10-29
    • 2015-01-18
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多