实现这一点的一种方法是使用pre_get_posts
有条件地添加single_template
和archive_template
过滤器。
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;
}