2017-08-29 204 views
1

我有一個簡碼,我想從特定的Woocommerce類別獲得所有產品。按照產品類別在WooCommerce的簡碼中獲取產品

add_shortcode('list-products', 'prod_listing_params'); 
function prod_listing_params($atts) { 
ob_start(); 

extract(shortcode_atts(array (
    'type' => 'product', 
    'order' => 'date', 
    'orderby' => 'title', 
    'posts' => -1, 
    'category' => '', 
), $atts)); 

$options = array(
    'post_type' => $type, 
    'order' => $order, 
    'orderby' => $orderby, 
    'posts_per_page' => $posts, 
    'product_cat' => $product_cat, 
); 
$query = new WP_Query($options); 
if ($query->have_posts()) { ?> 
    <div class="#"> 
     <?php while ($query->have_posts()) : $query->the_post(); ?> 
     <p class="#"> 
     <span id="post-<?php the_ID(); ?>" <?php post_class(); ?>> 
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
     </span></p> 
     <?php endwhile; 
     wp_reset_postdata(); ?> 
    </div> 
<?php 
    $myvar = ob_get_clean(); 
    return $myvar; 
} 
} 

於是我就用短碼:

[list-products category="shoes"] 

但是,儘管在短碼提供的類別返回全部來自所有類別產品。

我該如何修改這個以獲得分類?

感謝

回答

1

而不是'product_cat' => $product_cat,你應該使用tax_query這樣:

'tax_query' => array(array(
    'taxonomy' => 'product_cat', 
    'field' => 'slug', 
     'terms' => $atts['cat'], 
)), 

所以,你的代碼應該是這樣(我已經重新審視了一下你的代碼)

// Creating a shortcode that displays a random product image/thumbail 
if(!function_exists('prod_listing_params')) { 
    function prod_listing_params($atts) { 
     ob_start(); 

     $atts = shortcode_atts(array (
      'type' => 'product', 
      'order' => 'date', 
      'orderby' => 'title', 
      'posts' => -1, 
      'category' => '', // category slug 
     ), $atts, 'list_products'); 

     $query = new WP_Query(array(
      'post_type' => $atts['type'], 
      'order' => $atts['order'], 
      'orderby' => $atts['orderby'], 
      'posts_per_page' => $atts['posts'], 
      'tax_query' => array(array(
       'taxonomy' => 'product_cat', 
       'field' => 'slug', 
        'terms' => $atts['category'], 
      )), 
     )); 

     if ($query->have_posts()) { 
      ?> 
       <div class="#"> 
        <?php while ($query->have_posts()) : $query->the_post(); ?> 
        <p class="#"> 
        <span id="post-<?php the_ID(); ?>" <?php post_class(); ?>> 
         <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> 
        </span></p> 
        <?php endwhile; 
        wp_reset_postdata(); ?> 
       </div> 
      <?php 
      $myvar = ob_get_clean(); 
      return $myvar; 
     } 
    } 
    add_shortcode('list_products', 'prod_listing_params'); 
} 

C ode在你的活動子主題(或主題)的function.php文件中,或者也在任何插件文件中。

實例:

[list_products category="shoes"] 

相關的答案:

+0

完美!謝謝 –

1

您還可以使用WooCommerce自己提供的簡碼

[product_category category="appliances"] 
+0

是的,我遇到的唯一問題是,我的主題開始提供自己的風格,而且我會改變它來顯示產品變體,而不用換個新頁面。但你的回答站起來歡呼! –