WooCommerce:将循环中的购物车按钮文本更改为图标

WooCommerce: change cart button text in loop to icon

我想将存档页面上的购物车按钮文本更改为图标。

我找到了一个可以做到这一点的片段。但这也改变了购物车按钮的 link:

add_filter( 'woocommerce_loop_add_to_cart_link', 'ts_replace_add_to_cart_button', 10, 2 );
function ts_replace_add_to_cart_button( $button, $product ) {
    if (is_product_category() || is_shop()) {
        $button_text = __("View Product", "woocommerce");
        $button_link = $product->get_permalink();
        $button = '<a href="' . $button_link . '">' . $button_text . '</a>';
    return $button;
    }
}

有没有办法只更改按钮的文本?

我知道,我可以更改模板文件 /loop/add-to-cart.php。但是我需要一个基于函数的解决方案。

这应该可以解决问题。您可以调整条件语句。现在它覆盖了任何 taxonomy.php 页面,这是产品 (Woocommerce) 的存档页面,以及常规 archive.php 页面。

<?php
/**
* do_action( 'wp_customize_add_to_cart_archive' )
* This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated.
* @link https://developer.wordpress.org/reference/hooks/wp_loaded/
*/
add_action( 'wp_customize_add_to_cart_archive', function() {
  function wp_customize_add_to_cart_archive( $subject ) {
    if( ! is_admin() && is_archive() || is_tax() ) {
      $search = [
        '/>Add to cart</', // ... >< with the brackets, to be sure to target the right Home word
        // ... etc.
      ];
      $replace = [
        '><i class="fas fa-play-circle"></i><', // ... Our replacement for Add to cart using a font awesome icon
        // ... etc.
      ];
      $subject = preg_replace( $search, $replace, $subject );
      return $subject;
    };
  };
  ob_start( 'wp_customize_add_to_cart_archive' );
} ); ?>

了解更多