wordpress functions.php 为两个单独的自定义包含不同的脚本和样式 headers

wordpress functions.php to include different scripts and styles for two separate custom headers

我正在开发一个 wordpress 网络应用程序,并希望有 2 个不同的 header 文件可供我使用,具体取决于我所在网站的哪个部分。例如,如果未登录则显示自定义 header#1,如果登录则显示自定义 header#2。我想使用functions.php 文件。问题是我需要在每个 header 文件上调用 wp_head() ,这意味着它们将加载相同的脚本和文件。如有任何建议,我们将不胜感激。

function wpd_enqueue_scripts() {
    if( is_user_logged_in() ){
        wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/logged-in.js', array(), '1.0.0', true );
 wp_enqueue_style( 'twentythirteen-bootstrap.min', get_template_directory_uri() . '/css/bootstrap.min.css', array(), 'v3.1.0' );
    } else {
        wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/not-logged-in.js', array(), '1.0.0', true );
 wp_enqueue_style( 'twentythirteen-bootstrap.min', get_template_directory_uri() . '/css/bootstrap.min1.css', array(), 'v3.1.0' );
    }
}
add_action( 'wp_enqueue_scripts', 'wpd_enqueue_scripts' );

WordPress 的 get_header() 函数可用于通过传入参数来包含不同的 header 模板。示例:

// index.php
get_header(); // Will include header.php.

// some-template.php
get_header('other'); // Will include header-other.php.

当 header 依赖于模板文件时,这是首选的方法。例如,如果您需要为登录用户显示不同的 header,以下是一个快速解决方案:

if (is_user_logged_in()) :
    get_header(); // Includes header.php.
else :
    get_header('guest'); // Includes header-guest.php.
endif;

要将不同的脚本和样式排入不同的模板和页面,您只需挂接到 wp_enqueue_scripts 挂钩并使用 WP 条件确定要注册和排入的内容:

add_action('wp_enqueue_scripts', function () {
    wp_register_script('script-for-home', $urltoscript, ...);
    wp_register_script('script-for-page', $urltoscript, ...);
    wp_register_script('script-for-template', $urltoscript, ...);

    if (is_home()) {
        wp_enqueue_script('script-for-home');
    } elseif (is_page()) {
        wp_enqueue_script('script-for-page');
    } elseif (is_page_template('template.php')) {
        wp_enqueue_script('script-for-template');
    }
});

wp-admin 中的条件排队有点棘手,但请查看 wp_get_current_screen 以检查当前管理页面。