WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

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?

share|improve this question
up vote 4 down vote accepted
foreach((get_the_category()) as $category) { 
    if( file_exists( '/path/to/file/to/include/' . $category->cat_ID . '.php' ) )
        include( '/path/to/file/to/include/' . $category->cat_ID . '.php' );

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.


If you instead want to use custom functions on a per category basis you could do something like this:

// Create one function like this for each category
function my_custom_category_50(){
  // Do some awesome stuff.

// Use this to loop through the categories
foreach((get_the_category()) as $category) { 
  $func = 'my_custom_category_' . $category->cat_ID;
  if( function_exists( $func )

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.

share|improve this answer
That does indeed do the trick. Thanks for the quick response! Regarding a large number of categories, I have about 25, does that seem reasonable to you? – PDR Mar 15 '11 at 17:52
25 isn't too terribly much, but you might consider instead using a function based solution. I'll update my answer. – John P Bloch Mar 15 '11 at 18:04

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.