WP_Query lets you fetch posts with your own rules, like a specific category, post type or number of items, and display them anywhere in your theme.

Basic custom loop

<?php
$lotgrafix_query = new WP_Query( array(
    'post_type'           => 'post',
    'posts_per_page'      => 6,
    'category_name'       => 'news',
    'orderby'             => 'date',
    'order'               => 'DESC',
    'ignore_sticky_posts' => true,
) );

if ( $lotgrafix_query->have_posts() ) :
    while ( $lotgrafix_query->have_posts() ) :
        $lotgrafix_query->the_post();
        ?>
        <article>
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <?php the_excerpt(); ?>
        </article>
        <?php
    endwhile;
    wp_reset_postdata();
else :
    echo '<p>No posts found.</p>';
endif;
?>

Always call wp_reset_postdata() after the loop so the rest of the page keeps working.

Common arguments

  • post_type: a post type name or an array of names.
  • posts_per_page: how many posts. Use -1 for all.
  • cat, category_name, tag: filter by category or tag.
  • author: filter by author ID.
  • post__in and post__not_in: include or exclude specific IDs.
  • orderby: date, title, rand, comment_count, meta_value.
  • paged: the page number for pagination.

Filter by a custom field

$lotgrafix_query = new WP_Query( array(
    'post_type'  => 'post',
    'meta_key'   => '_lotgrafix_featured',
    'meta_value' => '1',
) );

Filter by a taxonomy

$lotgrafix_query = new WP_Query( array(
    'post_type' => 'lotgrafix_portfolio',
    'tax_query' => array(
        array(
            'taxonomy' => 'lotgrafix_project_type',
            'field'    => 'slug',
            'terms'    => 'websites',
        ),
    ),
) );

Change the main query instead of creating a new one

To modify the default blog or archive loop, use the pre_get_posts hook. Never use query_posts().

function lotgrafix_modify_main_query( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
        $query->set( 'posts_per_page', 9 );
    }
}
add_action( 'pre_get_posts', 'lotgrafix_modify_main_query' );
«
»