If you’ve built a plugin for WooCommerce before you may have come across the ‘message’ functionality which let you add messages (or errors) to the frontend using:
$woocommerce->add_message( 'Hi there' )
$woocommerce->add_error( 'You bafoon' );
Part of the development of WooCommerce 2.1 was refactoring the main
WooCommerce class which involved moving out unrelated methods (such as the messages) and moving them into their own classes.
We’ve replaced this particular functionality with some new functions and a new notices API which is much more flexible. The old methods are deprecated.
Understanding notice types
The first major change if the introduction of notice types. In 2.0.x there were two types; message and error, and these had there own methods making it very inflexible. 2.1 introduces notice types meaning you can have as many different types as you want. 2.1 itself uses the following three:
A ‘success’ message when something is successful, for example after adding an item to the cart, or getting a shipping quote.
An ‘error’ message triggered when something goes wrong, either user fault or code.
A generic notice type which is neither an error nor a success message.
Adding a notice
The main new function is
wc_add_notice. This is called passing the message itself, and the notice type:
wc_add_notice( $message, $notice_type = 'success' );
Once added, the notice is queued and will be output and cleared when WooCommerce outputs notices before a loop.
Templates used by notices
As mentioned earlier, there are three types used by WooCommerce core – each of these types have a template file:
Each template outputs a list of notices of that particular type, and you can of course make your own types and use your own template files should the default three types not cover your needs.
Other Notice functions
Aside from adding notices, the API has several other notices related functions – these include:
wc_notice_count( $notice_type )– Returns the count of queued notices of the type you specify.
wc_get_notices( $notice_type )– Returns all queued notices (in an array) of the type you specify.
wc_clear_notices– Cleared all queued notices.
wc_print_notices– Outputs all queued notices. This is hooked in to
wc_print_notice( $message, $notice_type = 'success' )– Works in a similar wasy to wc_add_notice, however rather than queuing the notice, it outputs it immediately.
Using the new API
If you are developing for 2.1 only, these functions should be used going forward. If however you are still maintaining 2.0 support you will need to do a
function_exists() check prior to use.
Good luck with the new API