在WordPress中的页面模板中添加自定义CSS

25

你好,我需要帮助创建一个自定义的CSS文件用于我的页面模板。虽然有很多关于这个问题的主题,但每读一个主题,我就会得到更多信息并变得更加困惑。

我为TwentyFourteen主题创建了一个子主题,并添加了一个页面模板。如何向这个模板添加自定义的CSS?我发现把下面这段代码添加到子主题的functions.php中,可以选择适当的CSS类。但是我应该将这个类放在哪里呢?我看到有人说要把这个类添加到header.php中的body标签中,但我不确定这是否正确。这是正确的方法吗?

if (is_page_template( 'mytemplate.php' )){
$classes[] = 'myclass';
}
3个回答

33

使用is_page_template()条件语句有选择地加载CSS。

在下面的函数中,我们将钩入到wp_enqueue_scripts并检查我们是否在自定义页面模板上,以确定是否要加载其他CSS。

如果结果为true,我们将从主题内部的css/文件夹中加载名为page-template.css的CSS文件。更新路径以加载正确的文件。

function wpse_enqueue_page_template_styles() {
    if ( is_page_template( 'mytemplate.php' ) ) {
        wp_enqueue_style( 'page-template', get_stylesheet_directory_uri() . '/css/page-template.css' );
    }
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_page_template_styles' );

1
很好。谢谢Nathan提供这段代码片段,这正是我在寻找的!但是当我将其包含进去时,CSS文件没有加载。所以谷歌告诉我需要用get_stylesheet_directory_uri()替换get_template_directory_uri()。现在它完美地工作了! - theDrifter

15

这个解决方案怎么样?

<?php 
function mypage_head() {
    echo '<link rel="stylesheet" type="text/css" href="'.get_bloginfo('stylesheet_directory').'/includes/mypage.css">'."\n";
}
add_action('wp_head', 'mypage_head');
?>
<?php get_header(); ?>

你可以使用wp_head钩子将自定义的内容(Javascript、CSS等)添加到你的自定义模板中。我认为这种方式更好,因为所有的更改都包含在你的模板文件中,所以你不需要在其他地方进行检查。

我从这个解决方案中获得了启示:http://scratch99.com/wordpress/development/custom-page-template-external-css-file/


2
这个怎么样?
 function my_custom_styles() {

    wp_register_style( 'custom-styles', get_template_directory_uri().'/lib/styles/custom-styles.css' ) );

    if ( is_home ) {

    wp_enqueue_style( 'custom-styles' );
    }
 }

 add_action( 'wp_enqueue_scripts', 'my_custom_styles' );

我已经测试了这里给出的所有三个答案,它们都运行良好。有人知道哪一个更快、更好吗?


你可以随时提出一个单独的问题。 - Xantium

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接