Create Custom Category Templates in WordPress

You know how to add categories in WordPress and add different types of posts in each categories. So in your WordPress themes you want to show different types of page templates for different categories. Now I’m going to show a very easy tricks for this.

Step 1

Download Custom Category Templates Plugin and install it.

Step 2

Just like you create custom page templates, add this code to your page where you want to show posts for any category.

<?php /** * Category Template: Grid */ ?>

By adding this code you defined the template name Grid. You can set different names for different type of templates.

Step 3

Now go to your admin category page and add a new category. You will see a template option added there for selecting templates.

Step 4

Ok how to display the category posts into the template. Add this code to your page for get the selected category. It means when someone click on category link from the website, this code will get that category name.


<?php $category = get_the_category(); $current_category = $category[0]; ?>

 

 

If you want to show the category name then just use this


<?php echo $current_category->cat_name ; ?>

Step 5

Now I’m using WP_Query for run a loop and show all the posts of that selected category. Here is a sample of a code that I used on my project for display posts of a category.


<?php $args = array ( 'post_type' => 'post',
	'nopaging'               => false,
	'posts_per_page'         => '6',
	'category_name'         =>  $current_category->cat_name,
	'order'                  => 'DESC',
	'orderby'                => 'ID',
	'offset'=>4
);

$query = new WP_Query( $args );
?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<?php $feat_image_url = wp_get_attachment_url( get_post_thumbnail_id() ); ?>  





<div class="col-xs-6 padding-10">
   
<div class="grid-post">
	<a href="<?php the_permalink(); ?>" class="mb-20">
        <img src="<?php echo $feat_image_url;?>" alt="Tranding News">
         </a>

    
<div class="post-info padding-15 ptb-20 bd-grey">
			

     
<h4 class="mb-15 fw-6">
         <a href="<?php the_permalink(); ?>" class="text-dark"><?php the_title(); ?></a>
     </h4>


      <span class="date"><?php the_time( 'F jS, Y' ); ?></span>
    </div>

   </div>

</div>

                         
<?php endwhile; ?>
<?php endif; ?>

Hope it works. Thanks for reading this article.

Leave a Reply

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