YogeshChauhan.com

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

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.

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

What’s a Log File and What are Log File Monitors?MiscA quick introduction to API, REST API and PostmanMiscHow to check if a link has http or https in it in JavaScript?JavaScriptThe 8 Golden Rules of Programming I Have Learned in My CareerMiscWhat’s a repository on Github?MiscHow to create Glowing Text using CSS?CSSHow to create a Star Ratings using CSS?CSSModules and its Core features in JavaScriptJavaScriptIs there a way to do a FULL OUTER JOIN in MySQL?SQL/MySQLJavaScript Input Validation Theme Park Example using throw StatementJavaScriptSolution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software”MiscCSS align-items property examplesCSS