• Resolved soggybiscuit

    (@soggybiscuit)


    Hi

    I am using Members plugin and trying to restrict the viewing of one particular woocommerce product to a specific user role – so that anyone not logged in or not at the required user level doesn’t see it.

    Having tried every combination of settings possible, I have reached a dead end… anyone with the URL can view the product – logged in or not and regardless of user role.

    I am using Members 3.1.1

    Please can you assist?

    Many thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Caseproof

    (@caseproof)

    Hi @soggybiscuit

    Members doesn’t fully protect a product on the front-end as it protects post content. WooCommerce templates show post content (which will be protected), but it shows a lot more, such as price, short description, etc., which is usually post meta.
    That said, here’s a snippet that will hide a product from the loop and redirect it when the user doesn’t have a required role:

    add_filter( 'woocommerce_product_is_visible', 'members_maybe_remove_product_from_query', 95, 2 );
    /**
     * Removes a product from the query depending on if the user has the correct permission.
     *
     * @param boolean 	$is_visible 	Whether the product is visible
     * @param int 		$product_id 	Product ID
     *
     * @return boolean
     */
    function members_maybe_remove_product_from_query( $is_visible, $product_id ) {
    	return members_can_current_user_view_post( $product_id );
    }
    add_action( 'template_redirect', 'members_woocommerce_product_redirect' );
    /**
     * Redirects users to the shop page when they cannot view the current product.
     *
     * @return void
     */
    function members_woocommerce_product_redirect() {
    	if ( class_exists( 'WooCommerce' ) && is_singular( 'product' ) ) {
    		$post_id = get_the_ID();
    		if ( ! members_can_current_user_view_post( $post_id ) ) {
    			wp_redirect( apply_filters( 'members_woocommerce_product_redirect', get_permalink( wc_get_page_id( 'shop' ) ) ) );
    			exit;
    		}
    	}
    }

    Hopefully, that helps.

    Thread Starter soggybiscuit

    (@soggybiscuit)

    That’s absolutely excellent – thank you very much!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Woocommerce product show only to specific role’ is closed to new replies.