php - 使用 get_template_part 和 template_redirect 时出现在页脚下的模板中的重复内容
问题描述
我的 wp 设置是:
- php 7.4
- divi 主题和自定义子主题
<p>
当我在页面上正确编写内容显示时,我在我的子主题中制作了一个模板。但是当我在孩子的functions.php中添加一个函数以将变量传递给我的模板时,内容会在页面上显示两次:页脚上方和页脚下方。也许使用 template_redirect 不是正确的方法吗?
函数.php:
<?php
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function form_coav_date() {
$lucky = 'lucky';
set_query_var( 'lucky', $lucky );
get_template_part('coav-search', 'lucky');
}
add_action('template_redirect', 'form_coav_date');
我的模板 coav-search.php:
/*
Template Name: coav-search
*/
get_header();
echo '<div style="text-align:center;margin:20px 0;">';
echo '<p>';
echo 'Hello im the custom content, im very ' . $lucky . ' because i have a twin just below the de footer :)';
echo '</p>';
echo '</div>';
get_footer();
请注意,这是输出一个用于测试的变量,在我的真实代码中,我在 coav-search.php 中有一个表单,并在 functions.php 中处理此数据,除了内容显示两次外,它可以工作。
解决方案
看起来问题在于您试图将完整的模板文件作为模板部分包含在内。
get_template_part('coav-search', 'lucky')
将整个复制coav-search.php
到您所在的页面中,但该页面已经有页眉和页脚。
要将内容包含coav-search.php
到当前页面中,请将其设为模板部分 - 这仍然可以是单独的 php 文件,但它不是完整页面,因为它将包含在其他页面中。
您可以创建一个名为的文件coav-search-form.php
,例如,使用以下命令:
echo '<div style="text-align:center;margin:20px 0;">';
echo '<p>';
echo 'Hello im the custom content, im very ' . $lucky . ' because i have a twin just below the de footer :)';
echo '</p>';
echo '</div>';
现在你可以在你的template_redirect
和你的coav-search.php中使用它来在两个地方包含相同的代码。
coav-search.php:
/*
Template Name: coav-search
*/
get_header();
get_template_part('coav-search-form', 'lucky');
get_footer();
函数.php
function form_coav_date() {
$lucky = 'lucky';
set_query_var( 'lucky', $lucky );
get_template_part('coav-search-form', 'lucky');
}
add_action('template_redirect', 'form_coav_date');
推荐阅读
- url - 离线 PWA 中的 https://example.com/page.html?param=val 等 URL
- ios - RxSwift - 递归 Observables?
- windows - 为什么这会引发“读取访问冲突”?
- typescript - 打字稿:如何将对象强制转换或分配给属性较少的类型?(从大到小)
- amazon-web-services - 如果 Terraform 中没有特定子网,如何选择默认子网?
- ios - 用于匹配字符串中数字的小数部分并修改它的 Swift 正则表达式
- python - 使用特定维度作为键对排序列表进行排序
- ios - 当我通过我的应用程序打开 App Store 时,在 App Store 中显示打开的应用程序而不是更新应用程序
- c# - 仅当目标路径为空时,使用 pdfsharp 合并和保存 PDF 才有效
- python - 为什么 filechooser.selection 会添加一个额外的航点?