How to show posts under custom post type taxonomy?

Custom post types make things easier when you need something special done other than generic post or page. Here you can learn more about custom post types.

Long story short, suppose you have a real estate property listing website. You need to show properties based on property type in a page. Means you want to show Commercial and residential properties in a page. Then, you need to create a custom loop that will show properties under a custom post types taxonomy.

To do that, you need to define an argument first.

$args = array( 'post_type' => 'property', 
		'tax_query' => array(
			array(
				'taxonomy' => 'property-type',
				'field' => 'slug',
				'terms' => 'commercial'
			     )
			), 			
		'posts_per_page' => 10 
	    );

post_type: This is the custom post types name. The name exactly you have registered. In the example, I’ve used  property.

tax_query: tax_query takes an array of tax query arguments arrays. As property-type is a taxonomy we want to show, that’s why we need define its filed and terms name. “field” is to select taxonomy term by. Possible values are ‘term_id’, ‘name’, ‘slug’ or ‘term_taxonomy_id’. Default value is ‘term_id’. And the “terms” is axonomy term(s).

In the example, I have used slug and the taxonomy terms commercial as I want to show commercial properties in a page.

posts_per_page:  This is to for how many post you want to show in a page. The value will be in “int”. The value “-1” means unlimited posts.

Now, we need to create the default loop that will show the posts/properties anywhere you want to show. It can be custom page template or post or page. Here you go…


$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
/* Display Property for Home Page */
/* get_template_part('template-parts/property-for-home'); */
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;

Now add these spinnets together in a single.php , custom-single.php or custom page template. This is it.

Here is the look:

$args = array( 'post_type' => 'property', 
		'tax_query' => array(
			array(
				'taxonomy' => 'property-type',
				'field' => 'slug',
				'terms' => 'commercial'
			     )
			), 			
		'posts_per_page' => 10 
	    );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
/* Display Property for Home Page */
/* get_template_part('template-parts/property-for-home'); */
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;

Here is the result.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *