WordPress中文开发手册

WordPress主题开发 — 连接主题文件和目录

链接到核心主题文件

正如你所学到的,WordPress主题是从许多不同的模板文件构建的。 至少这通常会包含一个sidebar.php,header.php和footer.php。 这些被称为使用模板标签,例如:

  • get_header();
  • get_footer();
  • get_sidebar();

您可以通过命名文件sidebar-{your_custom_template} .php,header-{your_custom_template} .php和footer-{your_custom_template} .php来创建这些文件的自定义版本。 然后,您可以使用模板标签与自定义模板名称作为唯一的参数,如下所示:

  • get_header( 'your_custom_template' );
  • get_footer( 'your_custom_template' );
  • get_sidebar( 'your_custom_template' );

WordPress通过组合各种文件创建页面。 除了标题,页脚和侧边栏的标准文件外,您可以创建自定义模板文件,并使用get_template_part()在页面中的任何位置调用它们。 要在主题中创建自定义模板文件,请为文件提供适当的名称,并使用与标题,侧边栏和页脚文件相同的自定义模板系统:

slug-template.php

例如,如果要创建自定义模板来处理您的帖子内容,您可以创建一个名为content.php的模板文件,然后通过将文件名扩展为content-product.php来为产品内容添加特定的内容布局。 然后,您将在主题中加载此模板文件,如下所示:

get_template_part( 'content', 'product' );

如果您想添加更多的组织到您的模板,您可以将它们放置在您的主题目录中的自己的目录中。 例如,假设您为配置文件和位置添加了一些更多的内容模板,并将它们分组在其名为content-templates的目录中。

称为my-theme的主题的主题层次结构可能如下所示。 style.css和page.php都包含在上下文中。

  • themes
    • my-theme
      • content-templates
        • content-location.php
        • content-product.php
        • content-profile.php
      • style.css

要包括您的内容模板,请将目录名称添加到slug参数中,如下所示:

get_template_part( 'content-templates/content', 'location' );
get_template_part( 'content-templates/content', 'product' );
get_template_part( 'content-templates/content', 'profile' );

链接到主题目录

要链接到主题的目录,您可以使用以下功能:

get_theme_file_uri();

If you are not using a child theme, this function will return the full URI to your theme’s main folder. You can use this to reference sub-folders and files in your theme like this:

echo get_theme_file_uri( 'images/logo.png' );

如果您使用的是一个子主题,那么该函数将返回您的子主题中的文件的URI(如果存在)。 如果您的子主题中找不到文件,该函数将返回父主题中的文件的URI。 在分发主题或其他情况下,儿童主题可能活动或可能不活跃时,这一点特别重要。

要访问主题目录中文件的路径,可以使用以下功能:

get_theme_file_path();

像get_theme_file_uri()一样,如果子主题存在,它将访问该文件的路径。 如果在子主题中找不到文件,该函数将访问父主题中文件的路径。

在子主题中,您可以使用以下功能链接到父主题目录中的文件URI或路径:

  • get_parent_theme_file_uri();
  • get_parent_theme_file_path();

与get_theme_file_uri()一样,您可以参考这样的子文件夹和文件:

echo get_parent_theme_file_uri( 'images/logo.png' );
//or
echo get_parent_theme_file_path( 'images/logo.png' );

引用可能不存在的文件时要小心,因为这些函数将返回URI或文件路径,无论文件是否存在。 如果文件丢失,这些功能将返回一个断开的链接。

注意:在WordPress 4.7中引入了函数get_theme_file_uri(),get_theme_file_path(),get_parent_theme_file_uri(),get_parent_theme_file_path()。

对于以前的WordPress版本,请使用get_template_directory_uri(),get_template_directory(),get_stylesheet_directory_uri(),get_stylesheet_directory()。

请注意,较新的4.7函数作为检查过程的一部分运行较旧的功能,因此在可能时使用较新的功能是有意义的。

模板中的动态链接

无论您的永久链接设置如何,您可以通过参考其唯一的数字ID(在管理界面的几个页面中)动态链接到页面或发布页面

<a href="<?php echo get_permalink($ID); ?>">This is a link</a>

这是创建页面菜单的便捷方式,因为您可以稍后更改页面段,而不会中断链接,因为ID将保持不变。 但是,这可能会增加数据库查询。

Tags ,