【问题标题】:How to update woocommerce sale price with custom product attribute value?如何使用自定义产品属性值更新 woocommerce 销售价格?
【发布时间】:2020-11-19 22:10:29
【问题描述】:

我正在尝试使用名为“Cost_price”的自定义产品属性“值”为每个产品(简单和可变)更新元“销售价格”。 此自定义产品属性是与其他站点连接的 API,它会每周更改一次值(价格),因此当产品自定义属性更新时,代码应该能够更改“销售价格”中的价格。

add_filter( 'woocommerce_product_variation_get_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'conditional_product_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'conditional_product_sale_price', 10, 2 );

add_filter( 'woocommerce_variation_prices_sale_price', 'conditional_product_sale_price', 10, 2 );

global $product;
$new_price = array_shift( wc_get_product_terms( $product->id, 'pa_cost_price', array( 'fields' => 'names' ) ) );

function conditional_product_sale_price( $price, $product ) {
    if( is_admin() ) return $price;
            $price = $new_price;
    }
if( !empty($sale_price) ){
    update_post_meta( $product_id, '_sale_price', $new_price );
}
    return $price;

我在这里寻找不同的变体,但找不到任何有效的方法。有谁知道我做错了什么? P.S 我完全是个菜鸟。

【问题讨论】:

    标签: php wordpress api woocommerce getcustomattributes


    【解决方案1】:

    在过去的两天里,我一直在寻找答案,并在这里找到了关于 woocommerce 自定义代码变体的非常好的帖子。最后,我找到了解决问题的正确代码。

    我使用自定义字段而不是自定义产品属性,因为我不知道如何“获取自定义产品属性值”到此代码。这个解决方案也适合我。

    add_filter('woocommerce_product_get_price', 'custom_cost_price', 10, 2); 
        add_filter('woocommerce_product_get_regular_price', 'custom_cost_price', 10, 2 );
        // Variations
        add_filter('woocommerce_product_variation_get_regular_price', 'custom_cost_price', 10, 2 );
        add_filter('woocommerce_product_variation_get_price', 'custom_cost_price', 10, 2 );
        function custom_cost_price( $price, $product ) {
            if( $product->get_meta('_costprice') );
                $price = $product->get_meta('_costprice');
        
            return $price;
        }
        add_filter('woocommerce_variation_prices_price', 'custom_variable_cost_price', 99, 3 );
        add_filter('woocommerce_variation_prices_regular_price', 'custom_variable_cost_price', 99, 3 );
        function custom_variable_cost_price( $price, $variation, $product ) {
            // Delete product cached price  (if needed)
            // wc_delete_product_transients($variation->get_id());
             if( $product->get_meta('_costprice') );
                $price = $product->get_meta('_costprice');
        
            return $price;
        }
    

    感谢@LoicTheAztec,但有一件事我没有做......我应该添加woocommerce_get_variation_prices_hash 以允许刷新缓存的价格吗?

    【讨论】:

      猜你喜欢
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2019-09-16
      • 2018-01-22
      • 2019-04-23
      相关资源
      最近更新 更多