Software Developer

How to Do Something For a Specific Category in WordPress

If you’re making your own WordPress theme or template, sometimes you need to show something different for posts of one specific category. You may want to display different text or a different picture (within the loop), or even call a different header or different template file altogether (outside the loop) for a certain category. This tutorial shows you how to display some content for one category, and then show some other content for all other posts. This code works within the loop on any page, or outside the loop on the single.php template page or category.php template page. This code is referred to as a conditional statement.

See the following code:

<!-- Begin conditional statement  -->
<?php
if ( in_category('category-slug') ) { ?>

<!-- Do stuff for this category here.  -->


<?php
} else { ?>

<!-- Or else do this stuff for all other posts  -->

<?php } ?>

<!-- End conditional statement  -->

Take the lines of code above and make the following changes:

On line 3, replace the ‘category-slug’ with your own category slug. Leave in the single quotes, like this ‘your-own-category-slug’ .

Take the content you want to display for that category, and enter it below line 3 and before line 7. You can enter as many lines of code as need here. HTML can be entered as is, but remember to enclose any PHP with the proper PHP tags. Line 5 is only an HTML COMMENT. You can delete the entire line 5, or simply leave it there as a note to yourself. HTML COMMENTS will not hurt anything. If you leave the line 5 comment there, then place your own content below line 5 and before line 7.

Then take the regular content that you want to display for all other posts that are not in the category that you already specified, and enter that content below line 8 and above line 12. That’s it.

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]