-
-
Save rogierborst/2786753 to your computer and use it in GitHub Desktop.
Using the template_include filter in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :-)
https://gist.github.com/2787095