
How to use WP Query In WordPress 2025

Yuhda Ibrahim
Development Consultant
February 22, 2025
3 min read

How to use WP Query in WordPress in a passionate way!
On this post, we are going to learn how to use wp query in a passionate way, first of all we can create the arguments query like this:
$arr_related = array();
$args= array(
'post_type' => 'post',
'posts_per_page' => -1
);
I add $arr_related to “house” the post id so we can customize the array later if we needed it, next we are going to add the while code like this:
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
$post_id = get_the_ID();
array_push($arr_related, $post_id);
}
wp_reset_postdata();
So all you guys confusing why we add the post id into an array, why just not use the wp query default object, the while wp query code was not “clean” in my eyes when we use it to loop within the html code, also when we need some modification order or some logic, it will be hard to modify the wp query object array.
Next think we can do loop the array easyly like this:
foreach ($arr_related 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
}
So here we go, it was clean right?
Instead of using the “Wp Query” object and loop the html inside while loop default wp query, we push it into an array named $arr_related after that we can loop the $arr_related using foreach, I think it was cleaner right? it was also open the scalability like we can add acf relationship array into it, or we can do some checking into an array, since if we are using while loop wp query it was hard to modify the array, here the full code:
$arr_related = array();
$args= array(
'post_type' => 'post',
'posts_per_page' => -1
);
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
$post_id = get_the_ID();
array_push($arr_related, $post_id);
}
wp_reset_postdata();
foreach ($arr_related 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
}
See you on the next post!