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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #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
Data Flows in ReactReactHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPWordPress: How to setup and get values from an ACF options page?WordPressPHP arrays for US states’ full names and abbreviationsPHPHow to convert a number rounding to a specified number of decimals in JavaScript?JavaScriptA short basic guide on states in ReactReactHow to Write Complex Search Queries in SQL?SQL/MySQLA complete guide to add responsive YouTube videos using HTML and CSSCSSSubquery in PostgresPostgresCreate a responsive pricing table using simple HTML and CSSCSSWordPress: How to access first and random row values from a repeater field in ACF?WordPressHow to update database configurations in WordPress?WordPress