1

我正在尝试使用每个产品(简单和变量)的名为“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;

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

4

1 回答 1

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以允许刷新缓存的价格吗?

于 2020-11-22T09:13:21.220 回答