Search code examples
phpwordpressfunctionwoocommercehook-woocommerce

Wordpress 6.2.2: unable to get fontawesome (or even a svg) to work in add to cart button


I'm using the following to display fontawesome in the add to cart button,

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_button_text_single' );
function custom_add_to_cart_button_text_single( $button_text ) {
    $button_text = '<i class="fa fa-shopping-cart" aria-hidden="true"></i> Add to Cart';
    return $button_text;
}

how ever the <i class="fa fa-shopping-cart" aria-hidden="true"></i> displays as text as follows,

&lt;i class="fa fa-shopping-cart" aria-hidden="true"&gt;&lt;/i&gt;

I have fontawesome installed and when I edit the html using browser inspect and change

&lt;i class="fa fa-shopping-cart" aria-hidden="true"&gt;&lt;/i&gt;

to

<i class="fa fa-shopping-cart" aria-hidden="true"></i>

it displays.

I'm not sure what I need to do to get the code to work.


Solution

  • This is because the functions that have the woocommerce_product_single_add_to_cart_text filter are used by WooCommerce's templates, and use esc_html() to prevent HTML from displaying (ex: single-product/add-to-cart/simple.php).

    The better approach is to override WooCommerce templates in your theme, and change the button to not use the function, and instead use your Font Awesome icon.