WordPress:为每个 $pages 动态包含页面模板
WordPress: Include page template dynamically foreach $pages
我正在开发一个单页 wp 站点,使用创建的每个页面作为新的 slide/section 内容。我想为不同的幻灯片使用不同的模板,并且在动态包含每个模板时遇到了问题,但最终想出了如何去做。
原版php:
<?php
$pages = get_pages(array('sort_column' => 'menu_order'));
foreach ($pages as $page_data) {
$page_ID = $page_data->ID;
$template = get_current_template();
?>
<section id="<?php echo $slug ?>" class="slide cf">
<?php include($template) ?>
</section>
<?php
} /*end foreach*/
?>
新 php:
<?php
$pages = get_pages(array('sort_column' => 'menu_order'));
foreach ($pages as $page_data) {
$page_ID = $page_data->ID;
$template = get_page_template_slug( $page_ID );
?>
<section id="<?php echo $slug ?>" class="slide cf">
<?php include($template) ?>
</section>
<?php
} /*end foreach*/
?>
在模板中使用 include
或 require_once
不是 WordPress 方式。 (有关原因的更多信息,请参阅 this article) WordPress has exposed specific functions for this for a reason - use get_template_part
请注意,使用此功能,模板可以位于它们应该位于的位置 - 在主题文件夹中。使用 include,您不会从正确的位置加载它们(include 将从 index.php
所在的根文件夹加载,除非 $template
变量具有完整路径,否则会变得混乱并且难以维护)。
<?php
$pages = get_pages( array( 'sort_column' => 'menu_order' ) );
foreach ($pages as $page_data) {
$page_ID = $page_data->ID;
$template = get_page_template_slug( $page_ID );
?>
<section id="<?php echo $slug; ?>" class="slide cf">
<?php get_template_part($template); ?>
</section>
<?php } ?>
我正在开发一个单页 wp 站点,使用创建的每个页面作为新的 slide/section 内容。我想为不同的幻灯片使用不同的模板,并且在动态包含每个模板时遇到了问题,但最终想出了如何去做。
原版php:
<?php
$pages = get_pages(array('sort_column' => 'menu_order'));
foreach ($pages as $page_data) {
$page_ID = $page_data->ID;
$template = get_current_template();
?>
<section id="<?php echo $slug ?>" class="slide cf">
<?php include($template) ?>
</section>
<?php
} /*end foreach*/
?>
新 php:
<?php
$pages = get_pages(array('sort_column' => 'menu_order'));
foreach ($pages as $page_data) {
$page_ID = $page_data->ID;
$template = get_page_template_slug( $page_ID );
?>
<section id="<?php echo $slug ?>" class="slide cf">
<?php include($template) ?>
</section>
<?php
} /*end foreach*/
?>
在模板中使用 include
或 require_once
不是 WordPress 方式。 (有关原因的更多信息,请参阅 this article) WordPress has exposed specific functions for this for a reason - use get_template_part
请注意,使用此功能,模板可以位于它们应该位于的位置 - 在主题文件夹中。使用 include,您不会从正确的位置加载它们(include 将从 index.php
所在的根文件夹加载,除非 $template
变量具有完整路径,否则会变得混乱并且难以维护)。
<?php
$pages = get_pages( array( 'sort_column' => 'menu_order' ) );
foreach ($pages as $page_data) {
$page_ID = $page_data->ID;
$template = get_page_template_slug( $page_ID );
?>
<section id="<?php echo $slug; ?>" class="slide cf">
<?php get_template_part($template); ?>
</section>
<?php } ?>