
How to set WP Query using Category Taxonomy

Yuhda Ibrahim
Development Consultant
February 22, 2025
3 min read
Learn how to set up WP_Query using category taxonomy in WordPress. This guide covers query arguments, custom loops, and best practices for filtering posts by category.

On the previous post we already learn how to use wp query, now on this post we are going to learn how to use WP Query to only load by specific category,
Okay let’s start by creating the wp query argument:
$arr_post = array();
$args= array(
'post_type' => 'post',
'posts_per_page' => -1,
);
$wp_query = new WP_Query( $args );
Now we are going to add the argument “cat” into the wp query like this:
$arr_post = array();
$args= array(
'post_type' => 'post',
'posts_per_page' => -1,
'cat' => 2 // your cat id
);
$wp_query = new WP_Query( $args );
It will default to load all the post within category cat id == 2, after we set the argument wp query we can do while loop like this
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
$post_id = get_the_ID();
array_push($arr_post, $post_id);
}
wp_reset_postdata();
Much cleaner right? Instead we loop the html element inside while loop wordpress, we push the post id into array $arr_post, so next we just need to loop the $arr_post like this:
foreach ($arr_post as $key => $value) {
$post_date = get_the_date('', $value);
$post_title = get_the_title($value);
?>
<div class="item_blog_small">
<div class="title_area">
<p>Yuhda Ibrahim</p>
<p>Development Consultant</p>
</div>
<p><?php echo $post_date ?></p>
<div class="item_text_small">
<h3><?php echo $post_title ?></h3>
</div>
</div>
<?php
}
Now we are done learning how to use wp query using category taxonomy, we can explore more like using custom taxonomy, like “tax_query” on the arguments or we can use “orderby” argument to sort by title, date etc..
Here the list of full code:
$arr_post = array();
$args= array(
'post_type' => 'post',
'posts_per_page' => -1,
'cat' => 2 // your cat id
);
$wp_query = new WP_Query( $args );
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
$post_id = get_the_ID();
array_push($arr_post, $post_id);
}
wp_reset_postdata();
foreach ($arr_post as $key => $value) {
$post_date = get_the_date('', $value);
$post_title = get_the_title($value);
?>
<div class="item_blog_small">
<div class="title_area">
<p>Yuhda Ibrahim</p>
<p>Development Consultant</p>
</div>
<p><?php echo $post_date ?></p>
<div class="item_text_small">
<h3><?php echo $post_title ?></h3>
</div>
</div>
<?php
}
If you needed WordPress Support to help your website, contact us section are below this section!
See you on the next post!
Need wordpress developer help fix your website? Let’s talk here or you can contact directly here