This code restricts the purchase of products to the author of the WooCommerce product. This tutorial contains 2 separate solutions :
- The 1st uses the
woocommerce_add_to_cart_validationhook which enables you to add a custom notice - The 2nd uses the
woocommerce_is_purchasablehook which uses the default notice.
woocommerce_add_to_cart_validation
add_filter( 'woocommerce_add_to_cart_validation', 'restrict_purchase_to_author', 10, 3 );
function restrict_purchase_to_author( $passed, $product_id, $quantity ) {
// Get the product author (post author)
$product_author_id = get_post_field( 'post_author', $product_id );
// Get the current user ID
$current_user_id = get_current_user_id();
// Check if the current user is the author
if ( $current_user_id != $product_author_id ) {
// If not, prevent adding to cart and show an error message
wc_add_notice( __( 'You are not authorized to purchase this product.', 'woocommerce' ), 'error' );
$passed = false;
}
return $passed;
}
get_post_field('post_author', $product_id): Retrieves the author (user ID) of the product.get_current_user_id(): Retrieves the ID of the currently logged-in user.woocommerce_add_to_cart_validation: WooCommerce filter hook used to validate adding a product to the cart.wc_add_notice(): WooCommerce function to display an error notice if the user is not authorized to purchase the product.$passed: Boolean variable to control whether the product can be added to the cart (true for allowed, false for not allowed).
woocommerce_is_purchasable
add_filter( 'woocommerce_is_purchasable', 'wc_restrict_purchase_to_author', 10, 2 );
function wc_restrict_purchase_to_author( $is_purchasable, $product ) {
// Get the product author (post author)
$product_author_id = $product->post->post_author;
// Get the current user ID
$current_user_id = get_current_user_id();
// Check if the current user is the author
if ( $current_user_id != $product_author_id ) {
// If not, product is not purchasable
$is_purchasable = false;
}
return $is_purchasable;
}
woocommerce_is_purchasable: This filter hook is used to determine if a product is purchasable.$product->post->post_author: Retrieves the post author ID of the product. WooCommerce product objects store their post object, which contains the author ID.get_current_user_id(): Retrieves the ID of the currently logged-in user.$is_purchasable: Boolean variable to control whether the product is purchasable (true for purchasable, false for not purchasable).
Modify this line to target who can and cannot add the product to cart :
if ( $current_user_id != $product_author_id ) {
Was this helpful?
Thanks for your feedback!

Leave a Reply
You must be logged in to post a comment.