How to redirect user to a page after form submission

I have three dropdown filters on the front site to select country, territory and region and need to redirect the user to the country/territory/region page depending upon the filter values on click of Submit button.

FYI, I have pages with the same slug.eg- example.com/country-name/territory-name/region-name

I am trying to use wp_redirect( $final_url ); exit; but it is throwing a warning-

Warning: Cannot modify header information – headers already sent by (output started at E:\path\to\root-folder\wp-includes\class.wp-styles.php:154) in E:\path\to\root-folder\wp-includes\pluggable.php on line 1121

Please help.

Can someone suggest me some some better way?

//Edit-
here is my code

if(isset($_POST['submit']) and $_POST['action']=='findurl')
    {
        //Result $POST Array ( [countrySelect] => 1 [territorySelect] => 1 [regionSelect] => 2 )
        if (isset($_POST['countrySelect'])){

            $rows_country_url = $wpdb->get_results("select url from country where id=".$_POST['countrySelect']."");
        }

        if (isset($_POST['territorySelect'])){

            $rows_territory_url = $wpdb->get_results("select url from territory where id=".$_POST['territorySelect']."");
        }

        if (isset($_POST['regionSelect'])){

            $rows_region_url = $wpdb->get_results("select url from region where id=".$_POST['regionSelect']."");
        }


        if($rows_country_url[0]->url !=''){
        $final_url = home_url("https://wordpress.stackexchange.com/").$rows_country_url[0]->url;}

        if($rows_territory_url[0]->url !=''){
        $final_url = $final_url."https://wordpress.stackexchange.com/".$rows_territory_url[0]->url;}

        if($rows_region_url[0]->url !=''){
        $final_url = $final_url."https://wordpress.stackexchange.com/".$rows_region_url[0]->url;}

        echo $final_url;

        if($final_url!=''){ 
        wp_redirect( home_url() ); exit;
        echo "not blank";
        }else{ echo "Please select values";}
    }

2 Answers
2

Please make sure these is no data output or blank spaces above wp_redirect( $final_url ); exit; otherwise this warning will always appear.

Also optionally you can use

<?php
//Php code 
 ?>
<script type="text/javascript">
      document.location.href="http://example.com";
</script>
<?php
//php code
?>

Leave a Comment