只有当该类别中的帖子大于/等于 3 时,我才努力使用此代码来显示类别(带有帖子)。
我使用带有 args() 的 WP_Query 来获取类别并显示这些类别中的最新 3 个帖子。
任何帮助将不胜感激。
<?php
$categories = get_categories( $args );
foreach( $categories as $category ) {
$args = array(
'cat' => $category->term_id,
'posts_per_page' => 3,
'post_type' => 'post',
);
$terms = get_terms(array(
'taxonomy' => 'category'
) );
foreach($terms as $term) {
if($term->count >= 3) {
echo $term->name;
$the_query = new WP_Query( $args );
echo '<h3>' . $category->name . '</h3>'; // Display category name
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</h3>
<?php
endwhile;
}
}
}
wp_reset_postdata();
?>
答案 0 :(得分:1)
WP_Query 将返回特定类别的帖子,而不是类别本身。
您需要获取所有类别并遍历它们并检查计数。
https://developer.wordpress.org/reference/functions/get_terms/
它应该是这样的:(未经测试!)
$terms = get_terms(array(
'taxonomy' => 'category'
) );
foreach($terms as $term) {
if($term->count >= 3) {
echo $term->name;
}
}
$categories = get_terms( array(
'taxonomy' => 'category',
'hide_empty' => false,
));
foreach ($categories as $category) {
$args = array(
'cat' => $category->term_id,
'posts_per_page' => -1,
'post_type' => 'post'
);
if ($category->count >= 3) {
echo $category->name;
$the_query = new WP_Query($args);
echo '<h3>' . $category->name . '</h3>'; // Display category name
while ($the_query->have_posts()) : $the_query->the_post();
?>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</h3>
<?php
endwhile;
}
}
wp_reset_postdata();
get_terms() 数组可以接受很多参数,因此请先查看文档。
如果您有任何问题,请告诉我。我会尽力提供帮助:)