-
-
Save rogierborst/2786753 to your computer and use it in GitHub Desktop.
<?php | |
add_filter( 'template_include', 'ja_template_include' ); | |
function ja_template_include( $template ) { | |
if ( !is_category() ) | |
return $template; | |
$category_info = get_category(get_query_var('cat')); | |
if ( $category_info->parent == 0 ) | |
return $template; | |
$parent_cat = get_category($category_info->parent); | |
// construct a possible file url | |
$subcat_url = get_stylesheet_directory() . '/subcategory-' . $parent_cat->slug . '.php'; | |
// return that url if it exists. Otherwise, return the normal template | |
return is_file($subcat_url) ? $subcat_url : $template; | |
} |
Nice thought process.
Couple of things:
-
The
$subcat_url
variable is mis-named - it's not a URL, but a path to a file. -
I'd also add a conditional in that final return of
is_readable( $subcat_url )
, since you're currently only checking that the string looks like a path to a file, not that it resolves to a file that exists AND is readable. -
Some WP code standards and documentation :-)
Gary, thanks for the comments.
- You're absolutely right.
- I'm not sure why I used
is_file( $subcat_url )
, I'd usually check withfile_exists()
, butis_readable()
sounds like a good option, too. - WP code standards? Didn't know there were any, and not sure if I could be bothered tbh. Documentation on the other hand, yeah, should definitely add that.
So, I'm completely new to Gists. Should I fork the improvements? Can I do commits like in Git?
- http://codex.wordpress.org/WordPress_Coding_Standards
These are also programmatically testable using PHP_CodeSniffer and https://github.com/mrchrisadams/WordPress-Coding-Standards . My advice is that if you're creating snippets of code for others, then help save those who do have a want / requirement to follow the WP CS by writing your snippets with them. Same for documentation., which is why my fork also links back to the gist URL so they can see where it was likely copied from when they look at it in 6 months time.
If you want to improve your own gist above, then you can just Edit it (button near the top). If you want to start from my new fork (which is a fork from your code, which is a fork from my code, which is a fork from Jared), then you can just create new fork, as you did previously.
How could this be modified to include sub-categories of the sub-categories?
This will include sub-categories of sub-categories - https://gist.github.com/4643794
With this fork, you only need to include the function once. After that, you can create subcategory templates just by creating 'subcategory-' + <your parent category slug> php files (i.e. subcategory-news.php).
It works just like the standard WordPress templating system, where, if you have a file called 'category-news.php', it'll load that template instead of the normal 'category.php' template.