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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to make WordPress main stylesheet (style.css)?WordPressHow to apply style only to first child and/or only to children other than the first child?CSSWhat’s a Web Storage API in JavaScript?JavaScriptCSS Overflow Property with ExamplesCSSReverse a String in JavaScriptJavaScriptIntroduction to components and templates Part 3: Data bindingAngularHow to Make a Simple Module with a Form and Menu Link in Drupal 7.x?DrupalPHP Login System using PDO Part 1: Create User Registration PagePHPHow to embed YouTube or other video links in WordPress?WordPressHow to use $IF operator in Envision Basic?Envision BasicHow Do You Make a Private VPN?MiscellaneousSolution to pod install fails with json error on Mac OS X 10.15 (or Mac OS Catalina)Miscellaneous