我正在尝试设置类别页面,但我想显示当前属于该类别的产品。我不想为每个类别创建php模板
此时设置为
<?php $args = array(
\'post_type\' => \'product\',
\'posts_per_page\' => 10,
\'product_cat\' => \'cat1\'
);
$loop = new WP_Query( $args );
?>
有没有办法让product\\u cat找到当前所在页面的产品?
我的产品代码是:
<div class="row products-range search-space">
<?php while ( $loop->have_posts() ) : $loop->the_post();
global $product;?>
<div class="col-xs-12 col-sm-12 col-md-4">
<div class="box">
<div class="image">
<a href=""><img src="https://via.placeholder.com/600x400" class="img-responsive center-block" /></a>
</div>
<div class="info">
<h3><a href="product-detail.html"><?php the_title(); ?></a></h3>
<ul>
<li>13cm Reflex Foam/7cm Top layer</li>
<li>Mains Isolation/Battery backup</li>
<li>5 Year warranty on Mattress and Frame</li>
<li>FREE INSTALLATION and Demonstration</li>
</ul>
<a class="btn btn-success btn-lg btn-block" href="<?php get_permalink();?>">View</a>
</div>
</div>
</div>
<?php endwhile;
wp_reset_query();?>
</div>
</div>
最合适的回答,由SO网友:Pratik Patel 整理而成
尝试使用获取类别信息
$category = get_queried_object();
$cpt_cat = $category->term_id;
$args = array(
\'post_type\' => \'product\',
\'posts_per_page\' => 10,
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'term_id\',
\'terms\' => $cpt_cat,
),
),
);
// Custom query.
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
global $wpdb;
/* Start the Loop */
while ( $query->have_posts() ) : $query->the_post();
?>
// Put your HTML stuff here
<?php
}
endwhile;
// Restore original post data.
wp_reset_postdata();
} ?>
并在查询结果时使用类别id/slug。
希望这会有所帮助!