woocommerce- hide add to cart button for product a

2019-09-19 19:30发布

问题:

As a part of my custom plugin (based on woocommerce) development I have assigned authors to products and willing to hide the add to cart button for product authors, so that I can restrict authors from buying their own product.

For this I have tried the below code but i am not able to hide the add to cart button from authors.

add_action('after_setup_theme','user_filter_addtocart') ;
function user_filter_addtocart(){
    $user_id = get_current_user_id();
    $author_id = get_post_field('post_author', get_the_ID());
    if(get_current_user_id() === $author_id){
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30, 3 );
    }
}

回答1:

You can try this, if your are using default shop and single product page it will work, and if you are using custom template for those pages then please make sure you are using default hooks and filters correctly in your custom template.

/* remove add-to-cart from shop page for product author  */
add_action('woocommerce_after_shop_loop_item_title','user_filter_addtocart_for_shop_page') ;
function user_filter_addtocart_for_shop_page(){
    $user_id = get_current_user_id();
    $author_id = get_post_field('post_author', get_the_ID());
    if($user_id == $author_id){
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    }
}

/* remove add-to-cart from single product  page for product author  */
add_action('woocommerce_before_single_product_summary','user_filter_addtocart_for_single_product_page') ;
function user_filter_addtocart_for_single_product_page(){
    $user_id = get_current_user_id();
    $author_id = get_post_field('post_author', get_the_ID());
    if($user_id == $author_id){
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}