Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted
<?php 
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.

EDIT

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

<?php
// 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 )
    $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
add comment

Your Answer

 
discard

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.