So I'm making some custom code to Allow specific producut purchase based on points accumulated from WooCommerce's points and rewards plugin, when checking the points balance, I'm using wc_add_notice to display the error if their balance is not enough. It worked the first time, then I can no longer get those notices, I tried executing it in multiple different ways, nothing seems to work !
Here's my code :
function enforce_points_based_registration( $valid, $product_id ) {
if ( $product_id == 4465 ) {
$points_required = get_post_meta( $product_id, 'points_required', true);
$user_id = get_current_user_id();
$user_points = WC_Points_Rewards_Manager::get_users_points( $user_id );
$current_user= wp_get_current_user();
$user_email = $current_user->email;
if ( wc_customer_bought_product( $user_email, $user_id, $product_id )) {
$message = "You have already bought the Vendor package";
wc_add_notice( apply_filters('wc_add_to_cart_message', $message, $product_id), "error");
return false;
}
if ( dokan_is_user_vendor( $user_id) ) {
$message = "You are already a vendor.";
wc_add_notice( apply_filters('wc_add_to_cart_message', $message, $product_id), "error");
return false;
}
if ( $user_points < $points_required ) {
// User doesn't have enough points, prevent purchase
$message = "You don't have enough points to purchase the subscription";
wc_add_notice( apply_filters( 'wc_add_to_cart_message', $message, $product_id ), "error" );
return false;
} else {
// User has enough points, place the order
$product = wc_get_product( $product_id );
$order = wc_create_order();
$order->add_product( $product, 1 );
$order->set_customer_id( $user_id );
$order->calculate_totals();
$order->update_status( 'completed' );
// Deduct points
WC_Points_Rewards_Manager::decrease_points( $user_id, $points_required, 'vendor_registration', $order->get_id() );
// Add custom message to the order notes
$order->add_order_note( apply_filters( 'wc_add_to_cart_message', "The order was automatically placed and paid for using points.", $product_id ) );
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'enforce_points_based_registration', 10, 2 );
I tried calling it that way with apply_filters, which worked the first time, I also tried wc_add_notice($message,$type) still nothing seems to work, although most of the code works as expected.
The code is placed in functions.php ( Child theme )
The filter hook
wc_add_to_cart_messagedoesn't exist in WooCommerce, so you should remove it from all wc_add_notice() functions in your code, as it can be the source of your issue, and doesn't provide anything useful.I have revised your code, try the following:
It may work now.