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

[ad_1]

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.

[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads