我使用以下代码在页面中列出我的类别:
<?php
$terms = get_terms( array(
'taxonomy' => 'category',
'hide_empty' => true,
) );
$count = count($terms);
$categories = array();
if ($count > 0) :
foreach ($terms as $term) {
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'show_count' => 1,
'orderby' => 'rand',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'categorys',
'field' => 'slug',
'terms' => $term->slug
)
)
);
$post_from_category = new WP_Query( $args );
if( $post_from_category->have_posts() ){
$post_from_category->the_post();
}else{}
$term->slug;
$term->name; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('thumb-block'); ?>>
<a href="<?php echo bloginfo('url'); ?>?categories=<?php echo $term->slug; ?>" title="<?php echo $term->name; ?>">
<header class="entry-header">
<span class="category-title"><?php echo $term->name; ?></span>
</header><!-- .entry-header -->
</a>
</article><!-- #post-## -->
<?php }
endif; ?>
我的问题是:如何列出仅包含至少5个帖子的类别?
非常感谢!
答案 0 :(得分:1)
在foreach
循环中,您可以检查以确保$term->count
大于或等于5.还有一些我注意到的其他事项:
$categories
数组,但似乎不再使用它。if: endif;
和if{}
语句 - 坚持使用易于维护的语法。$terms
是否设置为真值而不是检查其数量。else{}
支票->have_posts()
次循环
$term
个对象变量。home_url()
代替bloginfo('url')
所有这一切,这应该让你开始:
<?php
$term_args = array(
'taxonomy' => 'category',
'hide_empty' => true,
);
if( $terms = get_terms( $term_args ) ){
foreach( $terms as $term ){
if( $term->count >= 5 ){
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'show_count' => 1,
'orderby' => 'rand',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'categorys',
'field' => 'slug',
'terms' => $term->slug
)
)
);
$post_from_category = new WP_Query( $args );
if( $post_from_category->have_posts() ){ $post_from_category->the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'thumb-block' ); ?>>
<a href="<?= home_url( "?categories={$term->slug}" ); ?>" title="<?= $term->name; ?>">
<header class="entry-header">
<span class="category-title"><?= $term->name; ?></span>
</header>
</a>
</article>
<?php }
}
}
}
?>