php - 使用 WooCommerce 中的 Hook 更新产品价格

标签 php wordpress woocommerce product price

当产品在 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 );
}

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

最佳答案

已更新 (2018 年 8 月)

您的代码是正确的,但 Hook 是为 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 文件中或任何插件文件中。

经过测试并有效...

关于php - 使用 WooCommerce 中的 Hook 更新产品价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47277671/

相关文章:

PHP 不会回显 JSON_ENCODE 除非我回显其他内容

php - 将数组的 var_dump 转换回数组变量

php - 将 esc_attr_e() 连接到 WordPress 中的变量问题

javascript - JQuery:隐藏除一个图像之外的所有图像,从第一个开始并滚动它

javascript - 如何将 "push notifications"发送到特定用户网页?

php - 如何显示分配相同类别的所有帖子?

php - 在两个页面上显示 Wordpress 帖子

php - 将空值插入 WordPress 数据库

php - 在 Woocommerce 3 中添加和管理产品自定义上传字段

php - 在 WooCommerce 中更改购物车总价