Woo-commerce变量常规和销售价格

时间:2013-05-02 07:26:30

标签: categories product woocommerce

我正在尝试显示可变产品的常规价格和促销价格。我知道它可以通过get_post_meta实现($ post-> ID,'_ regular_price',true);但它不仅仅是一个简单的产品可变产品。

我查看了课程,并且还看到了woocommerce在存储可变产品价格时更新_regular_price本身的后期元。

我有什么遗失的吗?

由于

3 个答案:

答案 0 :(得分:4)

解决此问题的最佳代码是:

    #Step 1: Get product varations
$available_variations = $product->get_available_variations();

#Step 2: Get product variation id
$variation_id=$available_variations[0]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation.

#Step 3: Create the variable product object
$variable_product1= new WC_Product_Variation( $variation_id );

#Step 4: You have the data. Have fun :)
$regular_price = $variable_product1 ->regular_price;
$sales_price = $variable_product1 ->sale_price;

答案 1 :(得分:0)

如果您的产品没有任何变化,您可以使用以下产品ID简单地获得产品价格: -

add_action('init', 'test');

function test() {
    global $woocommerce;

    $product = new WC_Product(268);
    echo $product->get_price();
} 

如果产品有变化且每种变化都有不同的价格,则需要使用变体ID获取价格。

答案 2 :(得分:0)

这是因为可变产品本身并不保留任何价格信息,而是另一种名为"product_variation"的子帖子的父项,每个子帖子都有自己的价格和变化信息。因此,如果您想在WP_Query循环中对可变产品的价格进行处理,则必须通过post_type => 'product_variation'过滤循环,然后可以从其post_parent属性访问其父ID以获取这些可变产品变体的其他相关信息,例如名称,描述,图像,...

这里是一个例子:

$query = new WP_Query(array(
    'post_type' => 'product_variation', // <<== here is the answer
    'posts_per_page' => 5,
        'post_status' => 'publish',
        'orderby' => 'meta_value_num',
        'meta_key' => '_price',
        'order' => 'asc',
        ));

while ($query->have_posts()) {
    $query->the_post();
    $pid = $query->post->ID;
    $parent = $query->post->post_parent;
    $price = get_post_meta($pid, '_price', true);
    $regular_price = get_post_meta($pid, '_regular_price', true);
    $sale_price = get_post_meta($pid, '_sale_price', true);
    $title_product = get_the_title($parent);
    $title_variation = get_the_title($pid);
    echo "$title_variation: $price <br />";
}
相关问题