πŸ““

Queries & Loops

Return to Clientβ€’Studio

Queries & Loops

πŸ’‘

How to query posts inside templates or modules

β›”

Custom queries should not be used with native wp templates like single.php, archive.php.

Custom queries are used to fetch posts or custom posts (like portfolio items, team members, quotes, products etc). Query format should be always simple as possible.

Simple query example

<?php $the_query = new WP_Query( 'post_type=post&posts_per_page=12' );
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<h3><?php the_title();?></h3>
<p><?php the_content(); ?></p>

<?php endwhile; endif;	wp_reset_postdata();	?>

More advanced query example

<?php
	$args = array (
		'post_type'              => array( 'post' ),
		'nopaging'               => false,
		'posts_per_page'         => '6',
		'ignore_sticky_posts'    => false,
		'post__not_in'           => array(get_the_ID())
	);

	$the_query = new WP_Query( $args );
	if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : 
	$the_query->the_post(); ?>

		<li>
			<?php get_template_part( 'loop', '' ); ?>
		</li>

	<?php endwhile; endif;	wp_reset_postdata();	?>