Loop through custom post type in WordPress

I’ve recently been working on a website where I had to loop through custom post type in WordPress.

Wordpress custom post types are very powerful, and yet very easy to setup. You can use them for sliders, products, testimonials, case studies and so on. They help you to separate various types of content. Being visually separated in the backend, custom post types make it a lot easier for clients to maintain their content.

Once you created your custom post types you will most likely will want to display them on a page looping through each of them. It is best to create a page template to use a loop going through your custom post types instead of using the default templates.  In that page template, insert the code below:

Loop through custom post type in WordPress

<?php $loop= new WP_Query( array( 'post_type'=> 'your_post_type', 'posts_per_page' => -1 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
Whatever you want to do in that loop
<?php endwhile; wp_reset_query(); ?>

The first line sets up a WordPress query to your SQL database, asks which custom post type you want to use (in this case ‘your_post_type’) and how many posts should be displayed (-1 means ‘display all posts’).

The rest of the code loops through the custom post types and does “Whatever you want to do in that loop”. This means you can insert your own code here, for instance a div with the title of the custom post type, or its content.

Hope you find this helpful.



IT Support Newcastle is brought to you by Transcendit Ltd, contact us on 0191 482 0444