WordPress:激活不同页面上的不同样式表

时间:2016-10-11 02:42:27

标签: css wordpress

为了将我的样式表链接到我的WordPress主题,我在customtheme / style.css中有以下内容:

@import url('bootstrap/bootstrap.min.css');
@import url('includes/styles1.css');
@import url('includes/styles2.css');

假设我只想在一个页面上加载styles1.css(比如主页),并在所有其他页面上加载styles2.css。反正有指定这个吗?

2 个答案:

答案 0 :(得分:2)

wp_register_stylewp_enqueue_style

工作原理:

wp_register_style允许您注册自己的样式表并为其提供自己的句柄。这使您能够做的是定义所有样式并根据需要加载它们。在许多情况下,您经常会在主题的生命周期的早期看到样式表,然后根据一些逻辑检查进行排队。

举个例子:

假设您有一些自定义短代码,但不想加载任何样式表,除非实际使用短代码本身:

functions.php

add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
    //Register the style
    wp_register_style('my-shortcode-styles', get_template_directory_uri() . '/css/shortcode-styles.css');
}
add_action('init', 'custom_init');
function custom_init()
{
    //Example shortcode
    add_shortcode('my_shortcode', 'custom_shortcode');
}
function custom_shortcode($atts, $content = null)
{
    //If registered style isn't loaded....
    if (!wp_style_is('my-shortcode-styles')) {
        //Enqueue it!
        wp_enqueue_style('my-shortcode-styles');
    }
    return 'My Shortcode!';
}

在大多数情况下,wp_enqueue_style就足够了。使用它,您可以一次注册和排队样式表:

add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
    //Register and enqueue the style
    wp_enqueue_style('my-shortcode-styles', get_template_directory_uri() . '/css/shortcode-styles.css');
}

在您的情况下,您可以执行一些快速逻辑检查以确定用户在加载相应样式表之前访问的页面:

add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
    if(is_home()){ //is_front_page() if you're using a Page for the home page
        //Load only on the home page
        wp_enqueue_style('home-styles', get_template_directory_uri() . '/css/styles1.css');
    }
    //Load everywhere else
    wp_enqueue_style('my-theme', get_template_directory_uri() . '/css/styles2.css');
}

快速注意:为了使样式表入队起作用,您的主题 必须 使用wp_headwp_footer。如果您的活动主题在其模板文件中缺少这些主题,则样式表排队将无法正常工作

另见:

答案 1 :(得分:1)

为什么要在不同的页面上加载不同的样式表?拥有最少的工作表会导致https://tools.pingdom.com和/或https://developers.google.com/speed/pagespeed/insights/得分更高,加载时间更快。只需针对不同的页面在一个样式表中定位特定的类或ID,您就是金色的。