Skip to main content

How to make woocommerce pages accessible to logged in users only

Sometimes we need to set up private online shop. The easiest and fastest way to set up an online shop is to set up WordPress with WooCommerce. In WordPress, we can easily add a functionality that prevents guest users to access the products/shop page. Here is the code which needs to be in functions.php in theme files.

function guest_user_redirect() {
    if (! is_user_logged_in() && (is_woocommerce() || is_cart() || is_checkout())) {
        wp_redirect(home_url()); 
        exit;
    }
}
add_action('template_redirect', 'guest_user_redirect');

Comments

Popular posts from this blog

Set WordPress custom excerpt from Rank Math SEO plugin

  Sometimes, we need to set different excerpts for showing posts on the blog page. In this post, we are going to share a piece of code that works perfectly to change a posts' excerpt programmatically.  function rankmath_post_excerpt(){         $id = get_the_ID();         $post_type = get_post_type( get_the_ID() );         if ($post_type == 'post') {             $meta_description = get_post_meta($id,'rank_math_description',true);             return $meta_description;          }else{             return;         }          } function check_for_rankmath_activation(){     if ( is_plugin_active( 'seo-by-rank-math/rank-math.php' ) ){         add_filter('get_the_excerpt', 'rankmath_post_excerpt' );         add_filter('t...

Hide a product from WooCommerce main shop page

 function custom_pre_get_posts_query( $q ) {     $tax_query = (array) $q->get( 'tax_query' );     $tax_query[] = array(            'taxonomy' => 'product_cat',            'field' => 'slug',            'terms' => array( 'buster' ), // Don't display products in the clothing category on the shop page.            'operator' => 'NOT IN'     );     if(is_shop()){     $q->set( 'tax_query', $tax_query );   }else{     return;   }      } add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );