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 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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
EXISTS and NOT EXISTS in PostgresPostgresHow to create a circle that follows a cursor using JavaScript and CSS?CSSWordPress: How to loop through a repeater field in ACF?WordPressIs there a way to do a FULL OUTER JOIN in MySQL?SQL/MySQLRecursive WITH Queries in Postgres (Common Table Expressions)PostgresHow to install Gulp with WordPress?WordPressWhat are partials in SCSS (Sass)?SCSSThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSHow to include CSS and JavaScript files in your WordPress plugin?WordPressHow to convert an HTML radio buttons into a toggle switch using CSS?CSSHow to verify your domain in Google Console with a TXT record?MiscellaneousList of social media icon logo color codes in HEXMiscellaneous