Support » Developing with WordPress » wp_redirect issue

  • Resolved gshell

    (@gshell)



    I don’t seem to be able to get wp_redirect to work as I expected. I would like to create a shortcode to automatically redirect users to a different page when they open certain pages or posts. I have created a child theme, and added the following to the functions.php file.

    function my_redirect_function() {
    wp_redirect( home_url() );
    }
    add_shortcode(‘Go-Home’, ‘my_redirect_function’);

    However when I enter that shortcode on the page that I want to be redirected, nothing happens.

    What am I missing?

    Thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • wp_redirect() needs to be fired before any output is sent to the browser, but by the time a Shortcode is parsed it’s too late.

    With the goal of wanting to redirect to page Y when viewing pages A, B, or C, you can use something like this:

    add_action( 'wp', function() {
    	// IDs of posts that when visited will be redirect
    	$to_redirect = array( 1, 10, 15, 19 );
    
    	// The destination when redirecting
    	$destination = home_url();
    
    	// If we're viewing a post where we should redirect, redirect
    	if ( in_array( get_the_ID(), $to_redirect ) && ! is_home() ) {
    		wp_redirect( $destination );
    	}
    });

    You can replace your existing code in your child theme’s functions.php with the above, and customize the variables as necessary, and you should be all set.

    Joy

    (@joyously)

    wp_redirect uses the header() function to redirect the page. By the time the shortcode is processed, the headers have already been sent, so nothing happens.
    Also, the default status code is a 302, which you likely don’t want to use for this. And the address can be external, so it vulnerable to open redirects if you pass it a location supplied by the user.

    Thank You

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.