I use this code to pull in an image based on a post’s category. Images are named after the category they represent, so a post in category 50 pulls in 50.jpg.
<?php
foreach((get_the_category()) as $category) {
echo '<img src="/path/to/file/' . $category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />';
}
?>
I’d like to be able to do the same but to include a php file (also named after the category – so 50.php using the above example).
What’s the best way to do this?
That should do the trick. If the file doesn’t exist, it just skips it. This can be expensive to do if you have a large amount of categories to loop through, though.
EDIT
If you instead want to use custom functions on a per category basis you could do something like this:
This method has the advantage of not requiring file inclusion. This advantage would be most visible if you’re hitting the same category multiple times per page load.