2017-09-20 50 views
2

在WooCommerce中,我使用腳本來顯示一些隨機產品,但現在我需要排除一個不需要在本節中出現的產品類別。通過php顯示隨機產品,不包括一個類別

這可以在我的代碼中完成嗎?

我的代碼:

<?php 
    global $product; 
    $args = array(
     'posts_per_page' => 4, 
     'orderby'   => 'rand', 
     'post_type'  => 'product' 
    ); 
    $random_products = get_posts($args); 

    foreach ($random_products as $post) : setup_postdata($post); ?> 
     <li class="single_product_lower_widget" style="list-style:none;"> 
     <a href="<?php the_permalink(); ?>"> 
      <span class="single_product_lower_widget_image"> 
      <?php the_post_thumbnail() ?> 
      <span class="product-title"><?php the_title(); ?></span> 
      </span> 
      <p><?php get_post_meta($post->ID, '_price', true); ?></p> 
     </a> 
     </li> 
    <?php 
    endforeach; 
    wp_reset_postdata(); 
?> 

回答

3

您需要使用'tax_query'(定義不需要的產品類別)這樣說:

<?php 
    // Set HERE your product category (to be excluded) 
    $category_slug = 'music' ; 
    $random_products = get_posts(array(
     'posts_per_page' => 4, 
     'orderby'   => 'rand', 
     'post_status'  => 'publish', 
     'post_type'  => 'product', 
     'tax_query' => array(array(
      'taxonomy' => 'product_cat', 
      'field' => 'slug', 
      'terms' => $category_slug, 
      'operator' => 'NOT IN', 
     )) 
    )); 

    foreach ($random_products as $post) : setup_postdata($post); 
?> 
    <li class="single_product_lower_widget" style="list-style:none;"> 
     <a href="<?php the_permalink(); ?>"> 
      <span class="single_product_lower_widget_image"> 
      <?php the_post_thumbnail() ?> 
      <span class="product-title"><?php the_title(); ?></span> 
      </span> 
      <p><?php get_post_meta($post->ID, '_price', true); ?></p> 
     </a> 
    </li> 
<?php 
    endforeach; 
    wp_reset_postdata(); 
?> 

測試和工程

+0

嗨,非常感謝!它非常完美! –

0
<?php 
// Set HERE your product category (to be excluded) 
$category_slug = 'music' ; 
$random_products = get_posts(array(
    'posts_per_page' => 4, 
    'orderby'   => 'rand', 
    'post_status'  => 'publish', 
    'post_type'  => 'product', 
    'tax_query' => array(array(
     'taxonomy' => 'product_cat', 
     'field' => 'slug', 
     'terms' => $category_slug, 
     'operator' => 'NOT IN', 
    )) 
)); 

foreach ($random_products as $post) : setup_postdata($post); 
?> 
<li class="single_product_lower_widget" style="list-style:none;"> 
    <a href="<?php the_permalink(); ?>"> 
     <span class="single_product_lower_widget_image"> 
     <?php the_post_thumbnail() ?> 
     <span class="product-title"><?php the_title(); ?></span> 
     </span> 
     <p><?php get_post_meta($post->ID, '_price', true); ?></p> 
    </a> 
</li> 
<?php 
endforeach; 
wp_reset_postdata(); 
?>