Display Posts from a Custom Taxonomy (Tag / Category) of a Custom Post Type

Since ver. 2.3 you could create custom Taxonomies and custom Post Types came in since ver. 3.0.

In simple terms, Taxonomies are classifications and Post Types are well, they are Post Types. For e.g. Pages and Posts are two default post types (there are 5 default post types) and Tags and Categories are default Taxonomies. You can read more about Taxonomies here and Post Types here.

For e.g: Movies could be a custom Post Type and Genre could be a Taxonomy and Genres like Drama, Comedy etc could be the terms.

Here is a code snippet to display posts that belong to a specific taxonomy in a specific post type:

<?php
$args = array(
  'posts_per_page'   => 10,    // Number of posts per page
  'post_type'     => 'classifieds',  // Custom Post Type like Movies
  'tax_query'     => array(
              array(
                'taxonomy' => 'classifieds_tags',  //Custom Taxonomy Name like Genre
                'field' => 'slug',
                'terms' => array( 
                  'books',  //Tags or Categories like Drama or Comedy
                  'houses'
                )
              )
            )
  );
  
$new = new WP_Query( $args );
  
if ( have_posts() ) while ($new->have_posts()) : $new->the_post(); ?>
  
  <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <h3 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
  
    <div class="entry-content">
      <?php the_content(); ?>
    </div><!-- .entry-content -->
  
  </div><!-- #post-## -->
  
<?php endwhile; // end of the loop. ?>

This is a crude version of the code. Referring to your archive.php (or index.php in some themes) should help you extend this further to best suit your theme.

Hello, I am Arun Basil Lal. Thank you for reading!

I am a WordPress product developer and creator of Image Attributes Pro. I am passionate about solving problems and travelling the world.

Divi WordPress Theme - My Review

Divi WordPress Theme
Divi is a WordPress theme that web designers do not want you to know. It comes with a drag-and-drop theme builder. You can build beautiful looking unique websites without touching a line of code. Just choose from one of the many pre-made layouts, or pick elements and arrange them any way you like.

Divi is every WordPress developer's wet dream. Surprise your clients with neat responsive websites and have fun building them.

Divi comes from Elegant Themes. If you enjoy building websites, you *need* an Elegant Themes membership. 87 beautiful themes and 5 plugins for the cost of less than a candy-bar each!


Note: I am an avid user of Divi myself and this is a honest review. I wouldn't recommend something that I do not personally find amazing.

Leave a Reply

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

*