通过php显示随机产品,不包括一个类别

时间:2017-09-20 16:40:29

标签: php wordpress woocommerce categories product

在WooCommerce中,我使用脚本显示了一些随机产品,但现在我需要排除一个我不需要在本节中出现的产品类别。

如何在我的代码中完成此操作?

我的代码:

If Saturday OrElse Sunday = x Then weekend

2 个答案:

答案 0 :(得分: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();
?>

经过测试和工作

答案 1 :(得分: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();
 ?>