You should redirect before rendering the page begins, so a custom shortcode on the page is too late.
You need a more direct approach, like this:
function tssupp_redirect() {
if ( !is_user_logged_in() && is_page('inaccessible') ) {
wp_redirect(home_url());
exit;
}
}
add_action('template_redirect', 'tssupp_redirect');
Here I am preventing guest users from seeing a page with a slug of 'inaccessible', but you can pass a page ID (or an array of page IDs or page slugs). That's for static pages. For other URLs you might need a different conditional tag to identify the current page: https://developer.wordpress.org/themes/basics/conditional-tags/
I made the changes as you suggested. I need it for a woocommerce product, so i create the code like this:-
add_action('redirect_home_condi', 'func_to_redirect');
function func_to_redirect() {
if ( !is_user_logged_in() && is_product() ) {
echo "Redirect to Home.";
wp_redirect(home_url());
exit();
}
}
But its still not working, to check code i echo something and "Redirect to Home." is showing but redirection in not working.
Please help to correct this.