wp post query loops
page basic template with loop
1
2
3
4
5
6
7
8
9
10
11
12
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ;?></h2>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
advanced loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php if(is_category('featured')): ?>class="featured-post"<?php endif; ?>>
<h1><?php the_title() ;?></h1>
<p>
Published on <?php the_time('M j, Y'); ?>
by <?php the_category(', '); ?>
in <?php the_category(', '); ?>
</p>
<?php the_content(); ?>
<?php comment_form(); ?>
<div class="prev-next-links">
<ul>
<li><?php next_post_link(); ?></li>
<li><?php previous_post_link(); ?></li>
</ul>
</div>
</article>
<?php endwhile; else: ?>
<p>Sorry, this post does not exist</p>
<?php endif; ?>
loop using query posts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php query_posts('showposts=1&post_type=post'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
<hr>
<?php rewind_posts(); ?>
<?php query_posts('showposts=3&offset=1&post_type=post'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ;?></h2>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
loop using wp query
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$args = array(
'pagename' => 'about-us'
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
more complex example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$args = array(
'author_name' => 'zgordon',
'orderby' => 'title',
'post_type' => 'workshops'
'year' => 2012
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
This post is licensed under CC BY 4.0 by the author.
Comments powered by Disqus.