After adding a product to the cart in WooCommmerce you get a notice saying:
“Product" has been added to your cart. View cart
The link element (View cart) is rendered first and the string element (“Product" has been added to your cart.) second. I'd like to switch these element so the string is rendered first and link second.
HTML:
<div class="woocommerce-message" role="alert">
<a href="http://example.com/cart/" class="button wc-forward">View cart</a> “Happy Ninja” has been added to your cart.</div>
</div>
Tried tracking down the code but got stuck at: https://github.com/woocommerce/woocommerce/blob/master/templates/notices/success.php
Looking for a snippet to add to functions.php
Try this:
add_filter( 'wc_add_to_cart_message_html', function( $message ) {
return preg_replace(
// Or use ^(<a href=".+?" class="button wc-forward">.+?</a>) *(.+)
'#^(<a href=".+?" class="button wc-forward">.+?</a>) +(.+)#',
'$2 $1',
trim( $message )
);
} );
If no plugins (or if the theme doesn't) modify the default HTML markup (as you can see on line #121 and line #123), the code above should work well.
[EDIT #3] Alternatively, you can completely re-generate the message/HTML, as in the following example:
add_filter( 'wc_add_to_cart_message_html', 'my_wc_add_to_cart_message_html', 10, 2 );
function my_wc_add_to_cart_message_html( $message, $products ) {
$titles = array();
$count = 0;
foreach ( $products as $product_id => $qty ) {
$titles[] = ( $qty > 1 ? absint( $qty ) . ' × ' : '' ) . sprintf( _x( '“%s”', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) );
$count += $qty;
}
$titles = array_filter( $titles );
$added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
// Output success messages - the "View cart" or "Continue shopping" link comes after the product link/info.
if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
$return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
$message = sprintf( '%s <a href="%s" class="button wc-forward">%s</a>', esc_html( $added_text ), esc_url( $return_to ), esc_html__( 'Continue shopping', 'woocommerce' ) );
} else {
$message = sprintf( '%s <a href="%s" class="button wc-forward">%s</a>', esc_html( $added_text ), esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View cart', 'woocommerce' ) );
}
return $message;
}
Hope that helps!