One way to accomplish this may be to use the pre_get_posts
to conditionally add the single_template
and archive_template
filters.
namespace StackExchange\WordPress;
/**
* Add filters for `single_template`, and `archive_template` for the tutorial and
* dashboard archives.
*/
function pre_get_posts( $query )
{
if( is_singular() )
{
$post_type = get_post_type();
if ( 'tutorial' === $post_type || 'dashboard' === $post_type) )
{
add_filter( 'single_template', __NAMESPACE__ . '\react_template' );
return $query;
}
}
if ( ! is_post_type_archive( [ 'tutorial', 'dashboard' ] ) )
{
return $query;
}
if( ! isset( $query->query[ 'post_type' ] )
{
return $query;
}
$post_type = $query->query['post_type'];
if ( 'tutorial' === $post_type || 'dashboard' === $post_type) )
{
add_filter( 'archive_template', __NAMESPACE__ . '\react_template' );
}
return $query;
}
add_action( 'pre_get_posts', __NAMESPACE__ . '\pre_get_posts' );
/**
* Return the React Template, if it exists
*/
function react_template( $template )
{
if ( file_exists( PLUGIN_DIR . 'templates/learning.php' ) )
{
return PLUGIN_DIR . 'templates/learning.php';
}
return $template;
}