WooCommerce add data- attribute to view cart button on success message

I’ve managed to change the html markup of the View Cart button on success message so I could add id="open_cart" to it, but I also want to add a data- attribute such as data-cart="open" to the html output, however only the id is returned.

Any ideas on how to add a data- attribute to it?

Read More
function my_add_to_cart_message() {
    if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) :

    $message = sprintf( '%s<a id="open_cart" data-target="open-cart"  href="%s" class="button">%s</a>', __( 'Successfully added to cart.' , 'woocommerce' ), esc_url( get_permalink( woocommerce_get_page_id( 'cart' ) ) ), __( 'View Cart', 'woocommerce' ) );

    return $message;

}
add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_message' );

This is what the function above returns:

<a id="open_cart" href="http://example.com/cart/" class="button wc-forward">Ver carrinho</a>

The data-cart="open" is ignored. Simply annoying.

Related posts

Leave a Reply

1 comment

  1. Here’s a quick explanation as to why this is happening.

    Take a look at the Woocommerce success.php template which is responsible for displaying the success messages.

    <?php foreach ( $messages as $message ) : ?>
        <div class="woocommerce-message"><?php echo wp_kses_post( $message ); ?></div>
    <?php endforeach; ?>
    

    The wp_kses_post() function sanitizes the output of the $message variable by checking for allowed tags and attributes.

    Here’s your solution:

    Add this snippet to your functions.php

    function my_filter_allowed_html($allowed, $context){
        if (is_array($context)) {
            return $allowed;
        }
    
        if ($context === 'post') { 
            $allowed['a']['data-cart'] = true;
        }
    
        return $allowed;
    }
    add_filter('wp_kses_allowed_html', 'my_filter_allowed_html', 10, 2);
    

    You need to hook into the wp_kses_allowed_html filter and add your data attribute so that the wp_kses_post() function doesn’t filter it out.