YogeshChauhan . com

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.

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Everything you need to know about ANY, SOME and ALL Operators in PostgresPostgresLearn to create profile card using HTML and CSSCSSWhat are Identifiers in JavaScript?JavaScriptSolution to “TypeError: ‘x’ is not iterable” in Angular 9AngularHow to load a module with configuration in SCSS?SCSSHow to get ACF values from custom post type?WordPressA Quick Guide to Object-Oriented Programming in PHPPHPRendering Elements in ReactReactHow to create a secure random number using JavaScript?JavaScriptShort-Circuit Evaluation in JavaScriptJavaScriptAll different methods for accessing elements in the DOM using JavaScriptJavaScriptNew to ┬áDrupal? Here’s What You Need to KnowDrupal