11

How to send some variables with wp_redirect() from function.php file in my theme folder?

if ( $post_id ) {
    $variable_to_send = '1';
    wp_redirect( home_url(), $variable_to_send );
    exit;
}

And on homepage I will catch the variable in if-else condition to show some confirmation or not depending if $variable_to_send = '1' or not.

How to do that in WordPress?

10

I'm afraid that you can't do it this way.

wp_redirect is a fancy way to send header Location and the second argument of this function is request status, and not custom variable. (404, 301, 302, and so on).

You can send some variables as get parameters. So you can do something like this:

if ( $post_id ) {
        $variable_to_send = '1';
        wp_redirect( home_url() .'?my_variable='.$variable_to_send );
        exit;
}

Then you can use these variables as $_GET['my_variable'] or register it as custom get variable.

  • 1
    You could also set a cookie, I suppose. – Ben Polinsky Jan 5 '17 at 19:35
  • You need to use add_query_arg to do it the WordPress way. – Shivanand Sharma Jan 16 at 6:16
  • @ShivanandSharma you may, but there is no need to use add_query_arg to add just one arg to URL without any other query args. – Krzysiek Dróżdż Jan 16 at 6:56
9

Late to the party with this one, but the "Wordpress way" to do it would use add_query_arg like so:

if ( $post_id ) {
    wp_redirect( esc_url( add_query_arg( 'variable_to_send', '1', home_url() ) ) );
    exit;
}

This will initiate a redirect to http://my.website/?variable_to_send=1. You'd be able to capture the variable, then, on the homepage (or blog page, depending on how your home_url() is setup) by accessing $_GET['variable_to_send'] in your PHP code.

If you're going to do this in functions.php, make sure to hook onto init or a similarly early hook or else you will get a "Headers already sent" error.

Hopefully this helps someone who stumbles across this post.

  • 5
    If you're redirecting to a local address, you should use wp_safe_redirect(). – Nathan Johnson Mar 23 '17 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.