【问题标题】:WordPress - get_template_directory() returning parent theme's urlWordPress - get_template_directory() 返回父主题的 url
【发布时间】:2017-02-06 17:02:03
【问题描述】:

我正在尝试在 PHP 文件中制作一个简短的 HTML 组件,以便稍后将其包含在网站的不同页面中。

我想使用get_template_directory(),因为我认为它会返回我实际主题的根 URL。我使用的主题是儿童主题。相反,它似乎正在返回父级的根目录 URL。

做这一切的正确方法是什么? 我试图将一段 HTML 作为带有一些按钮的组件包含在一些不同的页面中。但我没有将它作为插件包含在内。

我检查了我的子主题文件夹中的所有内容,AFAIK 看起来一切正常。

我在 function.php 中有这段代码,我认为从我之前在这里提出的上一个问题中可以确定。

<?php
add_action('wp_enqueue_scripts', 'adapt_child_enqueue_styles');
function adapt_child_enqueue_styles(){
    wp_dequeue_style('theme-responsive');
    wp_enqueue_style('theme-child-style', get_template_directory_uri().'/style.css');
    wp_enqueue_style('theme-child-responsive', get_stylesheet_directory_uri().'/css/responsive.css');
}
?>

【问题讨论】:

    标签: php html wordpress include


    【解决方案1】:

    不要使用 get_template_directory(),而是使用

    get_stylesheet_directory()
    

    这将返回子主题目录而不是父主题目录。在此处阅读更多信息https://codex.wordpress.org/Function_Reference/get_stylesheet_directory

    【讨论】:

      【解决方案2】:

      我正在尝试在 PHP 文件中创建一个简短的 HTML 组件以包含它 稍后在网站的不同页面中。

      您所描述的内容称为模板部分。虽然可以将include 语句与get_stylesheet_directory() 结合使用,但有更好的处理方法:get_template_part()

      正如另一位用户已经指出的那样;您目前面临的问题是由于使用了错误的功能。 get_template_directory() 将返回父主题的路径,而 get_stylesheeet_directory() 将返回当前/子主题的路径。

      使用包含的示例:

      include( get_stylesheet_directory() . '/my-template-part.php' );
      

      使用get_template_part()替换:

      get_template_part( 'my-template-part' );
      

      get_template_part() 函数比简单的包含语句更健壮。查看文档了解更多信息:https://developer.wordpress.org/reference/functions/get_template_part/

      【讨论】:

      • 我应该把部分php文件放在哪里?
      • 它将与您的主题根目录相关。如果您按照上面所示使用它,那么它将首先在您的子主题中查找 my-template-part.php。如果在那里找不到它,它将检查父主题。您可能希望将模板移动到文件夹中。例如。 get_template_part( 'template-parts/my-template-part' );
      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2014-05-07
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多