首页 > 解决方案 > 使用 get_template_part 和 template_redirect 时出现在页脚下的模板中的重复内容

问题描述

我的 wp 设置是:

<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 中处理此数据,除了内容显示两次外,它可以工作。

标签: phpwordpresstemplates

解决方案


看起来问题在于您试图将完整的模板文件作为模板部分包含在内。

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');

推荐阅读