首页 > 解决方案 > 将字体真棒图标添加到 Woocommerce 3 中的自定义添加到购物车按钮

问题描述

在 LoicTheAztec 的帮助下,我改变了 Add To Cart 的样式,

但是如何使用以下代码在按钮文本前面添加一个很棒的字体图标

// For Woocommerce version 3 and above only
add_filter( 'woocommerce_loop_add_to_cart_link', 'filter_loop_add_to_cart_link', 20, 3 );
function filter_loop_add_to_cart_link( $button, $product, $args = array() ) {
if( $product->is_in_stock() ) return $button;

// HERE set your button text (when product is not on stock)
$button_text = __('Not available', 'woocommerce');

// HERE set your button STYLING (when product is not on stock)
$color = "#777";      // Button text color
$background = "#aaa"; // Button background color


// Changing and disbling the button when products are not in stock
$style = 'color:'.$color.';background-color:'.$background.';cursor:not-allowed;';
return sprintf( '<a class="button disabled" style="%s">%s</a>', $style, $button_text );
}

标签: phpwordpressbuttonwoocommercefont-awesome

解决方案


首先,如果 Wordpress 中没有为您的主题启用字体真棒图标,您可能需要添加Better Font Awesome插件。

您可以在此fontawesome.com 图标库中选择任何图标代码

现在对您的代码进行非常小的更改,您将能够添加所需的图标和大小:

add_filter( 'woocommerce_loop_add_to_cart_link', 'filter_loop_add_to_cart_link', 20, 3 );
function filter_loop_add_to_cart_link( $button, $product, $args = array() ) {
    if( $product->is_in_stock() ) return $button;

    // HERE set your button text (when product is not on stock)
    $button_text = __('Not available', 'woocommerce');

    // HERE set your button STYLING (when product is not on stock)
    $color = "#555";      // Button text color
    $background = "#aaa"; // Button background color

    // HERE set your fontawesome icon code and size
    $icon = 'fa-ban';
    $size = 'fa-lg'; // large - To disable size use an empty value like $size = '';

    // Changing and disbling the button when products are not in stock
    $style = 'color:'.$color.';background-color:'.$background.';cursor:not-allowed;';
    return sprintf( '<a class="button disabled" style="%s"><i class="fa %s %s"></i> %s</a>', $style, $icon, $size, $button_text );
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

你会得到类似的东西:

在此处输入图像描述

字体真棒可能的大小值:

  • 最小:fa-xs
  • 更小:fa-sm
  • 更大:fa-lg
  • 最大(乘数)fa-2x:,……fa-3xfa-10x

推荐阅读