【问题标题】:Add custom css to a page template in wordpress将自定义 css 添加到 wordpress 中的页面模板
【发布时间】:2015-03-30 17:57:35
【问题描述】:

嗨 我需要一些帮助来为我的页面模板创建自定义 css 文件。 关于这个问题有很多主题,但我阅读的每个主题都会获得更多信息和更多困惑。

我为二十四主题创建了一个子主题并添加了一个页面模板。如何将自定义 CSS 添加到此模板。我发现 添加到子主题的functions.php的这段代码使用我的css选择适当的类。但是我如何以及在哪里放置这门课?我读到我必须将类添加到 header.php 中的 body 标记,但我不确定。这是正确的方法吗?

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

【问题讨论】:

    标签: php css wordpress


    【解决方案1】:

    使用 is_page_template() 条件选择性地加载 CSS。

    在下面的函数中,我们连接到 wp_enqueue_scripts 并检查我们是否在自定义页面模板上以确定是否加载额外的 CSS。

    如果结果为真,我们将从主题内的 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' );
    

    【讨论】:

    • 不错。感谢 Nathan 提供此代码 sn-p,这正是我想要的!但是当我包含它时,css文件没有加载。所以谷歌告诉我,我需要用 get_stylesheet_directory_uri() 替换 get_template_directory_uri()。现在它工作得很好!
    【解决方案2】:

    这个解决方案怎么样?

    <?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/ 获得此解决方案。

    【讨论】:

      【解决方案3】:

      这个怎么样?

       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' );
      

      我已经从这里测试了所有三个答案;而且它们都很好用。有谁知道哪个更快更好?

      【讨论】:

      • 您可以随时提出单独的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多