Interacting with WP_Query, listing more posts from the current category.

For a new project of mine I was creating a single.php for the blog side of the website. The website had a few specific categories for the blog, these being News, Races and Events.

Whenever you were reading a blog post under one of these categories, the sidebar should show readers more posts from that specific category. May it be News, Races or Events. So we needed a way to show only the posts from the category that particular post was tagged under.

I decided that interacting with WP_Query here would be the best thing to do. The next thing we need to do is, because we are on a single.php page we need to find out what category that post is in. We can do this by using the get_the_category function.


// Assign get_the_category to a variable
$catData = get_the_category();

Here we have simply just stored the wordpress function get_the_category(); to a variable $catData. This is so we can use it later. The next step is to get the Category ID, in WordPress Categories are counted as Taxonomies and we can get the ID by passing the get_the_category(); variable through the term_id. Like so:


// Assign get_the_category to a variable
$catData = get_the_category();
$catID = $catData[0]->term_id;

As you can see we have a ‘[0]’ within our $catData. This is because get_the_category returns an array of objects due to a post potentially having numerous categories. By using ‘0’ our array will just loop through the first category. Now that we have found our current category, no matter what post single.php we are on, this will show us the category for this post, which is great if there are going to be more categories created down the line. This is a good way to future proof the website.

The final bit is putting this all together within the WP_Query. So let’s do that:


// Assign get_the_category to a variable
$catData = get_the_category();
$catID = $catData[0]->term_id;
$query = new WP_Query('cat'=.$catID);
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo '
<ul>
	<li>' . get_the_title() . '</li>
</ul>
&nbsp;

';
}
} else {
// no posts found
}

This will simply loop through all the posts found in the current category and output them in a list item showing the title.

Leave a comment

Your email address will not be published. Required fields are marked *