Here is a tested and working solution to remove the "You cannot add another" message.
Background: Woocommerce does not expose direct hooks to all of its notices. The cart errors are actually hardcoded into class-wc-cart.php as thrown Exceptions.
When Error Exceptions are generated, they get added to a list of Notices that we can access, parse, and alter using the methods:
- wc_get_notices() returns all notices as an array
- wc_set_notices() lets you set the notices array directly
In order to access the notices and alter them, you need to hook an action that will fire after woocommerce has generated its notices, but BEFORE the page is displayed. You can do that with the action: woocommerce_before_template_part
Here is complete working code that specifically removes "You cannot add another" notices:
add_action('woocommerce_before_template_part', 'houx_filter_wc_notices');
function houx_filter_wc_notices(){
$noticeCollections = wc_get_notices();
/*DEBUGGING: Uncomment the following line to see a dump of all notices that woocommerce has generated for this page */
/*var_dump($noticeCollections);*/
/* noticeCollections is an array indexed by notice types. Possible types are: error, success, notice */
/* Each element contains a subarray of notices for the given type */
foreach($noticeCollections as $noticetype => $notices)
{
if($noticetype == 'error')
{
/* the following line removes all errors that contain 'You cannot add another'*/
/* if you want to filter additiona errors, just copy the line and change the text */
$filteredErrorNotices = array_filter($notices, function ($var) { return (stripos($var, 'You cannot add another') === false); });
$noticeCollections['error'] = $filteredErrorNotices;
}
}
/*DEBUGGING: Uncomment to see the filtered notices collection */
/*echo "<p>Filtered Notices:</p>";
var_dump($noticeCollections);*/
/*This line overrides woocommerce notices by changing them to our filtered set. */
wc_set_notices($noticeCollections);
}
Side note: If you wanted to add your own notice, you can use wc_add_notice(). You'll have to read the woocommerce documentation to see how it works:
wc_add_notice on WooCommerce docs
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…