In Brad Schiff’s Learn WordPress Udemy course there a few chapters that go over the WP Custom Query. These include “Section 6 – Chapter 24,” “Section 6 – Chapter 41,” and “Section 15 – Chapter 76.”
What is a normal/standard/default query?
WP knows how to query the database for a page or post or blog page. A custom query is where you tell WordPress the exact content you want to query, allowing you to load whatever you want, wherever you want.
A simple “while loop” queries for us by default:
<?php
while (have_posts()) {
the_post(); ?>
<li><?php the_title(); ?></li>
<?php }
?>
Whenever you begin writing a custom query you begin by creating a variable that creates a new instance of a “WP_Query” object. In the “while loop,” look inside of that variable:
<?php
$homepagePosts = new WP_Query(array(
// check out all available parameters in docs
'posts_per_page' => 2,
'category_name' => 'awards'
));
while ($homepagePosts->have_posts()) {
$homepagePosts->the_post(); ?>
<li><?php the_title(); ?></li>
<?php }
?>
We wouldn’t want to hard-code the category name since we want it to be whatever the category for the current post is. We can probably just create and reference a variable.
// Something like this?
// Couldn't get to work
$current_category = wp_get_post_terms( get_the_ID(), 'category' );
Querying can be an expensive operation so you want to consider refactoring your code to make it as efficient as possible.
I ended up copying the snippet below from this website
<div><?php
$rand_same_cat_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'rand',
'posts_per_page' => '1', // get 5 posts
'ignore_sticky_posts' => 1,
);
// This code snippet pasted in from
// https://www.wpexplorer.com/related-posts-category/
// Check for current post category and add tax_query to the query arguments
$cats = wp_get_post_terms( get_the_ID(), 'category' );
$cats_ids = array();
foreach( $cats as $wp_ecp_related_cat ) {
$cats_ids[] = $wp_ecp_related_cat->term_id;
}
if ( ! empty( $cats_ids ) ) {
$rand_same_cat_args['category__in'] = $cats_ids;
}
// back to my code that runs custom query of posts
$my_query_rand_same_cat = new WP_Query( $rand_same_cat_args );
// loop through posts for custom query
if ( $my_query_rand_same_cat->have_posts() ) :
while ( $my_query_rand_same_cat->have_posts() ) : $my_query_rand_same_cat->the_post();
// display article
?>
<div class="btn--centered"><a href="<?php the_permalink()?>">Random From Same Category<a></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</div>
Note the use of ‘category__in’ instead of ‘category_name’ as a key in the array.