WordPress Custom Loop WP_Query Tutorial | Updated 2021

WordPress Custom Loop WP_Query Tutorial

WordPress Custom Loop WP_Query Tutorial | Updated 2021



WordPress has a class called “WP_QUERY”. Using this class we can data get custom data for example if you want to get data you can pass argument and data will come back to you accordingly





You can pass “category id” or “category name”, “tag id” or “tag name”, “author id” or “author name” etc as an arguments. You can pass array of id’s as well



So if you want to get a list of posts from multiple categories you can pass “categories id’s” as an argument to wp_query. For a list of options available in wp_query, you can check this link





Wp_query example



So in WordPress normal loop looks something like this





 if(have_posts()):
         while(have_posts()): the_post();
               // to print post title
               the_title();
               // to print post content
               the_content();
        endwhile;
 endif;

Now when we use wp_query we pass category or any id like this



 // cat=1 means we are passing category id 1
 $codingPosts = new WP_Query('cat=1');
                    if($codingPosts->have_posts()):
                        while($codingPosts->have_posts()):         $codingPosts->the_post()
               // to print post title
               the_title();
               // to print post content
               the_content();
               
                        endwhile;
                    endif;    

So mainly we pass an argument to class and create an instance of that class. Using the variable we customize bit of our loop and display desired results. Check Example here for better understanding and downloading the sample code.





wp_query explained step by step