【问题标题】:Woo-commerce Variable Regular and Sale priceWoocommerce 可变常规和销售价格
【发布时间】:2018-12-30 10:13:52
【问题描述】:

我正在尝试显示可变产品的常规价格和销售价格。我知道它可以通过 get_post_meta( $post->ID, '_regular_price', true);但它不仅仅适用于可变产品。

我查看了这些类,还看到 woocommerce 在存储可变产品价格时会更新 _regular_price 本身的帖子元数据。

我有什么遗漏吗?

谢谢

【问题讨论】:

  • 我自己回答了。如果有人想知道,他们可以使用 get price html 然后使用此过滤器来修改输出...
  • [CODE]add_filter('woocommerce_get_price_html', 'wpa83367_price_html', 100, 2);函数 wpa83367_price_html( $price, $product ){ return 'Was:' 。 str_replace('', '现在:', $price); }[代码]

标签: categories product woocommerce


【解决方案1】:

解决这个问题的最佳代码是:

    #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;

【讨论】:

    【解决方案2】:

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

    add_action('init', 'test');
    
    function test() {
        global $woocommerce;
    
        $product = new WC_Product(268);
        echo $product->get_price();
    } 
    

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

    【讨论】:

      【解决方案3】:

      这是因为可变产品本身不保留任何价格信息,而是另一种名为 "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 />";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-15
        • 1970-01-01
        • 2018-12-06
        相关资源
        最近更新 更多