Maarten Cappaert
Maarten Cappaert

Reputation: 47

Customizing a WooCommerce notice with add_filter

I am trying to customize a WooCommerce notice. This is the notice I am trying to replace:

wc_add_notice( sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() ), 'error' )

Based on this helpful answer WooCommerce Notice Messages, how do I edit them?, I came up with this:

function my_woocommerce_membership_notice( $error ) {
    if ( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.' == $error ) {
        $error = '%s has been removed from your cart because you added a membership product. Please complete the membership purchase first.';
    }
    return $error;
}

add_filter( 'woocommerce_add_error', 'my_woocommerce_membership_notice' );

This results in HTTP500 errors and I can't figure out why exactly.

Thanks!

Upvotes: 1

Views: 3955

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253929

Searching about this question in internet, it appears that a lot of people have serious similar error issues trying to use similar things…

This error message is set in includes/class-wc-cart.php at line 238.

Looking at WC version 2.6 source code in includes/wc-notice-functions.php, wc_add_notice() is handling 2 variables: $message and $notice_type.

So here for $message variable we have:
sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() )
Instead of only:
'%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.'

%s is a string variable used by sprintf() to be replaced by $_product->get_title() value. But you can't use %s here anymore.
This could be a reason for your error issue. Instead of '%s has been… try 'An item has been….

Then based on this thread, using strpos() php function inside the condition, I have compiled this snippet, Without any guaranty:

function my_woocommerce_membership_notice( $message ) {
    if (strpos($message,'has been removed from your cart because it can no longer be purchased') !== false) {
        $message = 'An item has been removed from your cart because you added a membership product. Please complete the membership purchase first.';
    }
    return $message;
}
add_filter( 'woocommerce_add_error', 'my_woocommerce_membership_notice' );

Upvotes: 2

Related Questions