Yogesh Chauhan's Blog

WordPress: How to query all posts from custom post type and display them in a list?

in WordPress on March 18, 2021

We have seen few get_posts() function examples before. We can use same function with few arguments to get the list from custom post types.



<?php 

$posts = get_posts(array(
	'posts_per_page' => -1,
	'post_type'	 => 'custom_post_type'
));

if( $posts ): ?>
	
	<ul>
		
	<?php foreach( $posts as $post ): 
		
		setup_postdata( $post );
		
		?>
		<li>
			<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
		</li>
	
	<?php endforeach; ?>
	
	</ul>
	
	<?php wp_reset_postdata(); ?>

<?php endif; ?>



Why to use setup_postdata() and wp_reset_postdata()?

setup_postdata() sets up the global post data. It helps in formatting custom query results when we use custom query with Template tags.

wp_reset_postdata() function restores the global $post variable to the current post in the main query. That’s why we use it after looping through a separate query.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to add today’s date in HTML input date value using JavaScript?JavaScript3 Common Usability Mistakes In Web DesignUI/UXRelative Length Units in CSSCSSPre-defined DatePipe format options in Angular 9AngularWhat is Host Hardening and What are some Important Hardening Steps?MiscellaneousHow to position an image on top of another image using CSS?CSS@use rule in SCSS (Sass)SCSSAdd animated hamburgers menu using Hamburgers collection on GitHubCSSSQL Inner JoinSQL/MySQLHow SCSS (Sass) finds a module without a file extension?SCSSHow to create a placeholder loader (throbber) using CSS?CSSHow to catch .keypress() on body using jQuery?jQuery