Video Tutorial The WP_Query object
We will now return to the front and talk about an essential object in WordPress: the object WP_Query
. This class is used internally to retrieve the articles to display in the loop. But you can also use it in your theme to retrieve a list of articles according to specific criteria.
We will build our objects by passing in parameter a table containing the criteria of our research.
$ query = new WP_Query ((
'post__not_in' => 1,
'post_type' => 'post',
'posts_per_page' => 3,
'orderby' => 'rand',
'tax_query' => (
((
'taxonomy' => 'sport',
'terms' => (1, 10, 3)
)
),
'meta_query' => (
((
'key' => 'is_sponso',
'compare' => 'NOT EXISTS'
)
)
));
It will then be possible to retrieve the records using the methods have_posts ()
and the_post ()
.
while ($ query-> have_posts ()): $ query-> the_post ();
?>
We will however be very careful to "clean up" the modifications made by the_post ()
thanks to the method wp_reset_postdata ()
to avoid conflicts with other loops.