Skip to content

Instantly share code, notes, and snippets.

@jonschr

jonschr/plugin.php

Last active Nov 5, 2015
Embed
What would you like to do?
A snippet to assign a child theme template file if there is one for archive-cpt.php, fall back to the plugin file (archive-cpt.php) if not, and if there's no file in the plugin, then fall back to the default Wordpress template hierarchy.
<?php
//* Don't include the opening php tag
/**
* Return Section (for template selection)
* @link http://www.billerickson.net/code/helper-function-for-template-include-and-body-class/
*
* @param null
* @return string
*/
function prefix_return_section() {
if ( is_tax( 'therapist-location' ) )
return 'archive-therapist'; // we are returning the name of the template file with the .php stripped
if ( is_singular() )
return 'single-therapist';
return false;
}
/**
* Template Chooser
* Use CPT archive templates for taxonomies
* @link http://www.billerickson.net/code/use-same-template-for-taxonomy-and-cpt-archive/
*
* @param string, default template path
* @return string, modified template path
*
*/
function prefix_template_chooser( $template ) {
if ( prefix_return_section() ) {
//* Get the filename of the location in the theme where the override template would live
$template_in_theme = get_query_template( prefix_return_section() );
//* Get the filename of the location in the plugin where our default template lives
$template_in_plugin = dirname( __FILE__ ) . '/templates/' . prefix_return_section() . '.php';
//* If this specific template is in the theme, we'll use that as our first choice
if ( file_exists( $template_in_theme ) )
return $template_in_theme;
//* If this specific template is in the plugin, we'll use that next
if ( file_exists( $template_in_plugin ) )
return $template_in_plugin;
}
//* If we don't have either of those, we'll just return whatever the original $template value was
return $template;
}
add_filter( 'template_include', 'ther_template_chooser' );
/**
* Section Body Classes
* @author Bill Erickson
*
* @param array $classes
* @return array
*/
function prefix_section_body_classes( $classes ) {
if ( prefix_return_section() )
$classes[] = 'section-' . prefix_return_section();
return $classes;
}
add_filter( 'body_class', 'prefix_section_body_classes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment