简体   繁体   中英

Not able to redirect with wp_redirect

So I saw some posts on here about this like: https://wordpress.stackexchange.com/questions/46336/wp-redirect-function-is-not-working I tried the solution to no avail. I wrote a php function that returns a permalink located in my functions.php file, the user enters a zip code, the form sends user to another page /locations where the function is called and the zip code is passed in:

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;
}

Search form on my main page looks like this:

<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" />

Then in my /locations page I call my function to get a permalink and the wp_redirect function to redirect to the outputted permalink like this:

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

However when I try to search I get this error:

Warning: Cannot modify header information - headers already sent by (output started at /srv/bindings/bdc12884a5a545f1b029665fb0fc0d35/code/wp-includes/class.wp-styles.php:225) in /srv/bindings/bdc12884a5a545f1b029665fb0fc0d35/code/wp-includes/pluggable.php on line 1219

Am I calling this function in the wrong place? Has anyone run into this issue in the past?

Please go through this article where you can fix your issue. I had same issue a few years back and it worked after looking into this post. Header Fix Issue

While facing this issue, i had empty space before PHP statement opened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM