How to redirect visitor to a custom URL using PHP code in functions.php

The users have to be redirected to a custom URL which I already know (its part of the programming logic). I just need to know which WP function to use/ what php code to use to redirect the user to the new URL. This code will be executed within a php function in functions.php–> that function will first do some processing, and then send the user to the new URL

How do I do the above?

Note– I tried using wp_redirect but it does not work.

This is the code I tried to use (that did not work)–

       $redirecturl = get_post_type_archive_link('property');
       echo "\n\n Redirect URL for property posts=" + $redirecturl;
       wp_redirect( "http://" .  $redirecturl + "?post_type=property&search_keyword=" + $search_keyword ;

2 Answers

First, it is hard to believe that wp_redirect isn’t working, below some (example) code how to use it:

function wpse101952_redirect() {
  global $post;

    if( /*SOME CONDITIONAL LOGIC*/ ) { //examples: is_home() or is_single() or is_user_logged_in() or isset($_SESSION['some_var'])

        wp_redirect( /*SOME SPECIFIC URL*/ );

add_action( 'template_redirect', 'wpse101952_redirect' );

Second, there would be the question if that is the right approach for your case, but for that to decide you should elaborate on what you are trying to do a little bit more.


The function get_post_type_archive_link() gives you the complete permalink, you don’t need to add http:// and ?post_type=property:

   wp_redirect( $redirecturl . "?search_keyword=" . $search_keyword );

Leave a Comment