在wordPress主题开发中,have_post()是必须经常用到的循环,然而它的循环次数只能在后台设置->阅读页面进行修改.对于不懂代码的站长想要在一些特定情况下使用have_post()又不想受后台设置中的限制,就是个难题了.以下是小编在网上搜集到的方法,及自己在开发主题过程中使用的,给自己一个记录,给大家一份帮助.
1.正常的用法
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<!–PHP代码 –>
<?php endwhile; ?>
<?php endif; ?>
2.自定义循环次数的用法
<?php $args = array('cat' =>'-5' , //这里数组的用法可以看wp-query的详细解析
'posts_per_page' =>'7' ,);
$the_query = new WP_Query( $args);
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();?>
<div class="item">
<figure class="pull-left"><img style="width: 67px;height: 45px;" src="<?php echo catch_that_image() ?>" alt="<?php the_title()?>" /></figure>
<div class="pull-right content">
<h4><a href="<?php the_permalink() ?>" title="<?php the_title()?>"> <?php the_title()?></a> </h4>
<p class="meta"> <?php the_title()?></p>
</div>
</div>
<?php
}
} else {
echo "no result";
}wp_reset_postdata();?>
- 3用get_post和get_category()代替
-
<?php $posts1 = get_posts("category=14&numberposts=8"); $query_index = 0; ?> <?php if ($posts1) : ?> <?php foreach ($posts1 as $post) : $query_index++; setup_postdata($post); ?> <li> //这里写你自己要循环的html代码 </li> <?php endforeach; ?> <?php endif; ?><?php $display_categories = array(2); foreach ($display_categories as $category) { ?> <?php query_posts("showposts=8&cat=$category")?> <?php while (have_posts()) : the_post(); ?> <div class="span12 post no-margin-left "> //这里写你自己要循环的html代码 </div> <?php endwhile; ?> <?php } wp_reset_query();?>4.相关的设置每次循环输出不同信息
让第一篇文章显示摘要,而余下的显示标题--代码: <?php if (have_posts()) :$ashu_i=0;?> <!--检查是否有文章,并定义计数变量初始值为0 --> <?php while (have_posts()) : the_post();$ashu_i++;?> <!-- 开始循环,第一次循环$sahu_i为1,第二次为2,依次。。 --> <?php if($ashu_i==1){?> <!-- 如果是第一篇文章 --> <?php the_content();}else{?> <!-- 显示内容 --> <?php the_title();}?> <!-- 如果不是第一篇显示标题 --> <?php endwhile; ?> <!-- 一次while循环结束 --> <?php else : ?> <!--如果没有文章--> 此处显示未找到文章时的信息,比如404相关 <?php endif; ?> <!--if结束 -->5.默认主题使用方法
<main id="main" class="site-main" role="main">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/page/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</main><!-- #main -->
