首页 > 解决方案 > 无法使用 wp_redirect 重定向

问题描述

所以我在这里看到了一些关于这个的帖子:https ://wordpress.stackexchange.com/questions/46336/wp-redirect-function-is-not-working 我尝试了解决方案无济于事。我编写了一个 php 函数,该函数返回位于我的functions.php文件中的永久链接,用户输入邮政编码,表单将用户发送到/locations调用该函数并传入邮政编码的另一个页面:

function zip_search($userZip){

    $args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'Locations'
    );

$wp_query = new WP_Query($args); 

if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
      $zipField=get_field('zip_codes_services');

          $zipString = $zipField . ', ';        

          $array = explode(', ' , $zipString); //split string into array seperated by ', '

        foreach($array as $value) //loop over values
        {

            if($value==$userZip){
                $post_id = get_the_ID();
                $permalink=get_permalink($post_id);                 
                return ($permalink); //print
           }    

        }
       endwhile; 
       wp_reset_postdata(); 
endif;
}

我主页上的搜索表单如下所示:

<form action="/locations" method="get">
    <input class="form-control search-input"
        autocomplete="off"
        name="zipcode"
        type="text"
        value=""
        placeholder="Enter Zip Code" />
</form>
<input type="submit" />

然后在我的/locations页面中,我调用我的函数来获取永久链接,并调用 wp_redirect 函数来重定向到输出的永久链接,如下所示:

<?php
    $zipcode = ( isset($_GET['zipcode']) ?  $_GET['zipcode'] : '');
    echo zip_search($zipcode);
    $url = zip_search( $zipcode );
    wp_redirect($url);
    exit();
?>

但是,当我尝试搜索时,出现此错误:

警告:无法修改标头信息 - 标头已由 /srv/bindings/bdc12884a5a545f1b029665fb0fc0d35/code/wp-在第 1219 行包含/pluggable.php

我在错误的地方调用这个函数吗?过去有没有人遇到过这个问题?

标签: phpwordpress

解决方案


请阅读这篇文章,您可以在其中解决您的问题。几年前我也遇到过同样的问题,在查看这篇文章后它起作用了。 标题修复问题

在面对这个问题时,我在 PHP 语句打开之前有空白空间。


推荐阅读