Search code examples
phpwordpresshttp-redirectwoocommercerestriction

Restrict Contact page allowing only logged in users in WooCommerce


I am building a ecommerce website with WooCommerce (8.1.1) and Divi theme. I found how to restrict access to WooCommerce pages to log in users, but I want to restrict Contact Page, which I created, to WooCommerce log in users. I suppose I have to customize functions.php found here (How to restrict pages to a user in Woocommerce?) ? Any help is welcome, thanks.


Solution

  • Try the following, that will redirect unlogged users to My Account page, when trying to access the contact page:

    
    add_action('template_redirect', 'contact_page_unlogged_users_redirect');
    function contact_page_unlogged_users_redirect() {
        $targeted_page = 'contact'; // <== Set the desired page slug
    
        if ( ! is_user_logged_in() && is_page( $targeted_page ) ) {
            // feel free to customize the following line to suit your needs
            wp_redirect( get_permalink( wc_get_page_id( 'myaccount' ) ) );
            exit();
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). It should work.