简体   繁体   中英

restrict product page with product category 'x' WooCommerce

I wan't to restrict certain product pages from logged-out users or users with a specific role. The easiest way would probably be to check the category ID of the product page and if current_user_can('') than redirect to the main shop page.

However I don't really know where to start.. Should I add an action on init ? And how do I check for the current page product ID?

I thought I could get some data with a var_dump() But that resulted in nothing. I did this:

add_action('init', 'get_all_post_meta');

function get_all_post_meta() {
    //$meta = get_post_meta( get_the_ID() );
    global $post;
    var_dump('$post');
    $metavar = get_the_terms($post->ID);
    var_dump('$metavar');

}

But no results in my console.

Edit: I found my var_dump() was incorrect as it should be like var_dump($post); Continuing my quest now.

This is my solution so far, now I need to figure out how to remove a single product instead of them all.

add_action('wp_head', 'get_all_post_meta', 1 );

function get_all_post_meta() {

    global $post;
    $banned_cid = array(8);
    $current_cid = array();
    $metavar = get_the_terms($post->ID, 'product_cat');
    global $woocommerce;
    $redirect_url = 'http://www.example.nl/';


    if(current_user_can('subscriber') || current_user_can('manage_options')){}else if( is_product()){
        foreach ( $metavar as $term ) {
                        $cat_id .= $term->term_id.',';
                        array_push($current_cid, $term->term_id);
                    }
        var_dump($current_cid);

        $c = array_intersect($banned_cid, $current_cid);
            if (count($c) > 0) {    
                $woocommerce->cart->empty_cart(); 
                wp_redirect( $redirect_url, 302 );
                exit;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM