我正在尝试为自定义帖子类型创建一个循环,首先计算它包含多少帖子。如果它只包含一篇文章,它应该只显示文章的内容区域。如果帖子包含多篇帖子,则应显示循环中所有帖子的摘录。有人发现了吗?
WordPress Loop if/else
2 个回复
SO网友:Michael
https://codex.wordpress.org/Class_Reference/WP_Query#Properties
found_posts
是查询返回的帖子总数。示例代码:
<?php
$args = array( \'post_type\' => \'your_custom\' );
$custom_query = new WP_Query( $args );
if( $custom_query->have_posts() ) {
$number_of_posts = $custom_query->found_posts;
while( $custom_query->have_posts() ) {
$custom_query->the_post();
if( $number_of_posts == 1 ) {
the_content();
} else {
the_excerpt();
}
}
wp_reset_postdata();
}
?>
SO网友:Abdul Awal Uzzal
请尝试此代码(&P);让我知道结果(我还没有测试)
<?php
$post_query = new WP_Query(\'post_type=post\'); // replace the post type with your post type key
$total_posts_found = $post_query->found_posts;
if($total_posts_found < 2 && $total_posts_found > 0){
if($post_query->have_posts()) : while($post_query->have_posts()) : $post_query->the_post();
echo \'<h1>\'get_the_title().\'</h1>\';
echo get_the_content();
endwhile;
endif;
wp_reset_postdata();
} else {
if($post_query->have_posts()) : while($post_query->have_posts()) : $post_query->the_post();
echo \'<h1>\'get_the_title().\'</h1>\';
echo get_the_excerpt();
endwhile;
endif;
wp_reset_postdata();
}
?>