正确获取自定义模板目录的方法

时间:2018-06-18 10:55:13

标签: css wordpress

我有一个自定义模板,其中包含CSS文件所在的特定文件夹:

WP\wp-content\themes\tema\css

当我将文件添加到我的HTML文件时,它找不到该文件:

<link rel="stylesheet" type="text/css" href="/wp-content/themes/tema/css/style.css">

我遇到get_template_directory(),但我不知道如何实现这一点,以便我可以访问我的模板文件夹?

3 个答案:

答案 0 :(得分:2)

functions.php

中添加此内容
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
function theme_name_scripts() {
    wp_enqueue_style( 'st', get_stylesheet_directory_uri() . '/css/style.css', '', '0.0.1', 'all' );
}

答案 1 :(得分:2)

首先要指出的是get_template_directory()返回绝对路径而不是URL。

您需要使用get_template_directory_uri()get_stylesheet_directory_uri()

您的示例将如下所示:

<link rel="stylesheet" type="text/css" href="<?php echo get_template_directory_uri(); ?>/css/style.css">

要解决的第二件事是如何添加样式表。 Wordpress有一个非常有用的功能,它针对添加名为wp_enqueue_style()的样式表进行了优化。

不是手动将样式表添加到主题目录中的header.php,而是将其添加到functions.php文件中,如下所示:

add_action( 'wp_enqueue_scripts', 'so_my_custom_scripts' );
function so_my_custom_scripts() {
    wp_enqueue_style( 'my-custom-stylesheet', get_template_directory_uri() . '/css/style.css', array(), '20180618' );
}

答案 2 :(得分:1)

尝试使用代字号~来到这个网站的主根

&#13;
&#13;
<link rel="stylesheet" type="text/css" href="~/wp-content/themes/tema/css/style.css">
&#13;
&#13;
&#13;