How to load/include category templates based on conditionals?

This looks like a plain PHP question at the first sight, but there is also at least one WordPress issue. Let’s start with that.

You should not use include or TEMPLATEPATH in a theme. There are alternatives for include in WordPress: get_template_part() and locate_template(). And the constants TEMPLATEPATH and STYLESHEETPATH will be deprecated in the near future because they are too restricted.

In your case I would recommend to use locate_template(). It accepts three arguments:

  1. An array of $template_names.
  2. An argument to $load the file if it is found.
  3. A $require_once parameter. We ignore this for now.
    and $name. Then it searches for a file named "{$slug}-{$name}.php" in your current theme directory and includes it with locate_template().

The function returns a path if it found a file and an empty string otherwise.

Let’s say your template for a single post from category video is named single-cat-video.php and the default file is named single-cat-default.php (you should always use speaking file names).

Plus, you have an array of categories to search for:

$my_cats = array( 'diario', 'predicacion', 'audio', 'video' );

Now you just walk through these category array until you found a file:

$found = FALSE;
foreach ( $my_cats as $my_cat )
{
    if (
        // we are in a category from our array and …
        in_category( $my_cat )
        // … actually found a matching file.
        and locate_template( "single-cat-$my_cat.php", TRUE ) 
        )
    {
        // As we now know that we got a template and already ↑ included it,
        // we can set a flag to avoid loading the default template.
        $found = TRUE;

        // … and immediately stop searching.
        break;
    }
}

// no matching category or no file found. load the default template part
if ( ! $found )
{
    locate_template( "single-cat-default.php", TRUE );
}

This could be written in a more compact way, but I think it is easier to read now. To add a category you just create a new template and extend the array $my_cats without the need to touch the rest of the code.

tech