我希望在wordpress中的页面上显示所有类别中的最新产品,当我们在其中添加更多类别和产品时,则必须将其最新产品添加到(显示)在页面上。这个?请帮我。谢谢
jeff2mac 回答:WordPress:我想要所有类别中最新的一种产品显示在WordPress页面上吗?
首先,您需要使用hide_empty
至少发表一篇文章来获得所有产品类别。
然后遍历每个类别并针对每个类别运行查询以获取单个产品。
$args = array(
'orderby' => 'name','order' => 'ASC','hide_empty' => true
);
$product_categories = get_terms( 'product_cat',$args );
$count = count($product_categories);
if ( $count > 0 ){
foreach ( $product_categories as $product_category ) {
echo '<h4><a href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</a></h4>';
$args = array(
'posts_per_page' => 1,'post_status' => 'publish','post_type' => 'product','tax_query' => array(
'relation' => 'AND',array(
'taxonomy' => 'product_cat','field' => 'slug','terms' => $product_category->slug
)
),);
$products = new WP_Query( $args );
echo "<ul>";
while ( $products->have_posts() ) {
$products->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php
}
wp_reset_postdata();
echo "</ul>";
}
}