如何在 WordPress 中有条件地检查自定义单个 post 模板
How to conditionally check a custom single post template in WordPress
我正在使用以下函数调用自定义单曲 post 覆盖默认单曲 single.php
function call_different_single_post($single_template)
{
global $post;
$path = get_stylesheet_directory() . '/includes/templates' . '/';
$single_template = $path. 'single-1.php';
return $single_template;
}
add_filter('single_template', 'call_different_single_post');
它正在为单个 post 调用 single-1.php
模板。
现在我想有条件地检查这个模板,这样我就可以调用一些其他的js文件,比如
function call_cust_js_single(){
if( /*..this is single-1.php template..*/){
wp_register_script('cust-js', get_stylesheet_directory_uri() . 'custom.js', false, '1.0.0');
wp_enqueue_script('cust-js');
}
}
add_action('wp_enqueue_scripts', 'call_cust_js_single');
有一个 post 与此类似,但不能完全满足您的要求。这是 link here
这是有价值的代码:
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
$GLOBALS['current_theme_template'] = basename($t);
return $t;
}
function get_current_template( $echo = false ) {
if( !isset( $GLOBALS['current_theme_template'] ) )
return false;
if( $echo )
echo $GLOBALS['current_theme_template'];
else
return $GLOBALS['current_theme_template'];
}
现在您有了 get_current_template
函数,它将 return 模板文件的文件名。
现在编辑您的 header.php 文件,这是一个示例:
<?php if('single-1.php' == get_current_template())
{
//load your scripts here
} ?>
它不像您要找的那样干净,但我认为它会对您有所帮助。
我正在使用以下函数调用自定义单曲 post 覆盖默认单曲 single.php
function call_different_single_post($single_template)
{
global $post;
$path = get_stylesheet_directory() . '/includes/templates' . '/';
$single_template = $path. 'single-1.php';
return $single_template;
}
add_filter('single_template', 'call_different_single_post');
它正在为单个 post 调用 single-1.php
模板。
现在我想有条件地检查这个模板,这样我就可以调用一些其他的js文件,比如
function call_cust_js_single(){
if( /*..this is single-1.php template..*/){
wp_register_script('cust-js', get_stylesheet_directory_uri() . 'custom.js', false, '1.0.0');
wp_enqueue_script('cust-js');
}
}
add_action('wp_enqueue_scripts', 'call_cust_js_single');
有一个 post 与此类似,但不能完全满足您的要求。这是 link here
这是有价值的代码:
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
$GLOBALS['current_theme_template'] = basename($t);
return $t;
}
function get_current_template( $echo = false ) {
if( !isset( $GLOBALS['current_theme_template'] ) )
return false;
if( $echo )
echo $GLOBALS['current_theme_template'];
else
return $GLOBALS['current_theme_template'];
}
现在您有了 get_current_template
函数,它将 return 模板文件的文件名。
现在编辑您的 header.php 文件,这是一个示例:
<?php if('single-1.php' == get_current_template())
{
//load your scripts here
} ?>
它不像您要找的那样干净,但我认为它会对您有所帮助。