I would like to restrict the access to a product on my woocommerce website.
If user are not login, I want to redirect them to register page.
I'm using this code but all my products redirect to register page :
function wpse_131562_redirect() {
if (! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_single(1735) || is_checkout())
) {
// feel free to customize the following line to suit your needs
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');
To you think of Something ?
The reason it is redirecting from all products to the register page is that the wp_redirect
function is running on all page that use a Woocommerce template as you use is_woocommerce()
.
I think what you need is the following:
function reg_redirect(){
if( is_product(1735) && !is_user_logged_in() ) {
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
exit();
}
}
add_action('template_redirect', 'reg_redirect');
You can try to verify the operator is working properly!
You can change "&&" with "and", or just put one condition in the if statement: which means do the following:
(note that this will redirect all users, even the signed-in ones)
function wpse_131562_redirect() {
if ( is_single(1735)) {
// feel free t`enter code here`o customize the following line to suit your needs
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');
If the above code works for only the single product you target, then experiment with your operates.
A better solution is that you avoid is_signle(), it's reported that is_single doesn't work properly with WooCommerce, you can try the following:
function wpse_131562_redirect() {
global $post;
if ($post->ID = '1735' and !is_user_logged_in()) {
// whatever you try to do here for product id = 123 will work!
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
}
}
add_action('template_redirect', 'wpse_131562_redirect');