WordPress

Querying posts

Syntax#

  • $the_query = new WP_Query( $args );
  • $posts_array = get_posts( $args );

Parameters#

Parameter Description
$args (array) An array of needed arguments for a query - can be custom tailored to your needs, e.g. querying posts from only one category, from custom post type or even querying certain taxonomy
## Remarks#
Query arguments are numerous. WP_Query() codex page has a list of parameters. Some of them are

One of the most important thing to have in mind is:

Never use query_posts()

query_posts() overrides the main query, and can cause problems in the rest of your theme. Any time you need to modify the main query (or any query for that matter) is to use pre_get_posts filter. This will allow you to modify the query before it ran.

Also when you are querying posts, you should always reset it using wp_reset_postdata(). This will restore the global $post variable of the main query loop, and you won’t have any issues later on (such as categories being excluded, because in your secondary loop you’ve excluded them and forgot to reset the query).

Using WP_Query() object

Creating a separate instance of the WP_Query object is easy:

$query_args = array(
                'post_type' => 'post',
                'post_per_page' => 10
            ); 

$my_query = new WP_Query($query_args);

if( $my_query->have_posts() ):
    while( $my_query->have_posts() ): $my_query->the_post();
       //My custom query loop
    endwhile;
endif;

wp_reset_postdata();

Notice that you need to build the query arguments array to your specification. For more details, look at WP_Query codex page.

Using get_posts()

get_posts() is a wrapper for a separate instance of a WP_Query object. The returned value is an array of post object.

global $post;

$args = array(
    'numberposts' => 5,
    'offset'=> 1,
    'category' => 1
);

$myposts = get_posts( $args );

foreach( $myposts as $post ) :
    setup_postdata($post); ?>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php endforeach;
wp_reset_postdata(); ?>

For more info check out the get_posts() codex page.


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow