Custom queries in WordPress allow us to have a little more control over what we need.
For example, we could use a custom query to fetch posts from a certain category, with a certain post type and have it only display 2 posts per page. To do so we need to create a new query as follows:
$myPosts = new WP_Query();
This is object oriented programming, where we create a new object from a class. For example:
$dog = new Animal();
$cat = new Animal();
$dog->sleep();
$cat->run();
In the above example, objects (dog and cat) created from the class (Animal) will share the properties of that class. i.e. An animal can run, it can sleep and so on.
Similarly, in the first example in this post, we created an object called $myPosts that is created from the WP_Query class.
That alone isn’t sufficient. We need to modify the code a bit and customise it a bit by passing some arguments as follows:
$myPosts = new WP_Query(array(
'posts_per_page' = 2,
'category_name' = 'space',
'post_type' = 'page'
));
Now $myPosts has what we need but we haven’t printed it out yet. That can be done via the following code:
<?php
while( $myPosts->have_posts() ) {
$myPosts->the_post(); ?>
<p><?php the_title(); ?></p>
<?php } ?>
That’s it. This is a random example but I hope it helps to demonstrate how to form a simple custom WordPress Query.