我需要指导,因为我是新手。
因此,我在本地安装了 WordPress,并成功地创建了仅包含基本主题内容的自定义主题。
主题目录:wp-content/themes/custom-theme/
在这个目录中,我希望创建子目录(content/home
、content/blog
...),然后我希望我的页面从中读取子目录等
主页将从 custom-theme\content\home
读取,主目录文件夹包括 page.php
等文件。
我确实已经设法创建了一个名为 page-home.php
的模板文件,我将其作为模板父页面链接到我在 wordpress 中创建的新页面。我的问题是该目录中的文件没有被 Hook 。
代码来自 page-home.php
<?php
/*Template Name: Home - Parent Page */
?>
<?php get_header(); ?>
<div id="content-main">
<?php $contentSrc = "content/home"; ?>
<script>
window.contentSrc = '<?php echo $contentSrc; ?>';
</script>
<?php //get_template_part("page-home"); ?>
</div>
<?php get_footer(); ?>
这是我试过的。然后它应该 Hook 子目录 content/home 中的页面。
代码来自:content/home/page.php
<div id="home">
<div class="hook" data-hook="home-info"></div>
<div class="hook" data-hook="home-navi"></div>
</div>
这需要一个函数/js 才能工作,但这只是我需要什么以及我想要实现什么的想法。
任何指向此指南或提示的链接都将不胜感激,我到处都看过,但我只是找不到任何基于我的问题的简单或准确的主题。
也许有一种非常简单的方法,我很感兴趣。
最佳答案
WordPress 提供的工具之一是 get_template_part();
但是,这需要您在调用此函数的页面上使用 Wordpress 的循环。
来自文档:
Includes the named template part for a theme or if a name is specified then a specialized part will be included. If the theme contains no {slug}.php file then no template will be included.
The template is included using require, not require_once, so you may include the same template part multiple times.
与主题子文件夹一起使用
要将此功能用于主题目录中的子文件夹,只需在 slug 之前添加文件夹名称即可。例如,如果您的主题目录中有一个名为“partials”的文件夹,并且该子文件夹中有一个名为“content-page.php”的模板部分,您可以像这样使用 get_template_part():
<?php get_template_part( 'partials/content', 'page' ); ?>
使用PHP
您还可以使用简单的 include()
/require()
/等。使用以下代码:
<?php include( get_template_directory() . '/content/myfile.php'); ?>
此特定示例使用 get_template_directory()
函数来查找您的自定义主题路径。另一个(但仍然有用)的函数是 get_stylesheet_directory()
其他资源
关于javascript - WordPress自定义页面模板从子目录读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39724690/