I assume that you have looked at the docs: https://codex.wordpress.org/Shortcode_API
...which would show you the proper code to check for a shortcode. Let's say your shortcode is called 'redirectme'. So the code you would use in your functions.php would be something like:
// redirect for the [redirectme] shortcode
function redirect_me( $atts ){
// do something if the shortcode is found
}
add_shortcode( 'redirectme', 'redirect_me' );
The redirect_me function will be called if the shortcode [redirectme]
is found. You would then modify the function to do the needed redirect.
For instance, if you wanted to redirect to http://example.com/the-new-page , you would put this inside the redirect_me function
$url = 'http://example.com/the-new-page';
wp_redirect( $url );
exit;
Check out the docs on the wp_redirect
function: https://developer.wordpress.org/reference/functions/wp_redirect/ . Note that the exit
is required, or the rest of the code for that page will execute.
Added
As mentioned in a comment to this answer, the wp_redirect()
won't work - it will cause a 'Headers already sent' error. This is because output has already started before the wp_redirect()
function is called by the appearance of the shortcode in the content.
So, you have to buffer the output before WP starts sending output. You can do that with this code:
function app_output_buffer() {
ob_start();
}
add_action('init', 'app_output_buffer');
...which I got from here https://tommcfarlin.com/wp_redirect-headers-already-sent/ (see that for more info). And there are probably similar references to ob_start()
here. Because that function will 'fire' before WP output starts, the wp_redirect()
will work if fired by the shortcode.
So, add the above code to your functions.php file, and you will be able to do a wp_redirect()
after WP has started output.
Another approach would be to change the template used for the post/page to check for valid user login, and redirect if the user has not logged in. You still might need the ob_start()
function, depending on where you check for user login.
is_single()
conditional before checking if the shortcode exists or not.