【问题标题】:New style of cart button when item is in cart in WooCommerce当商品在 WooCommerce 中的购物车中时,新样式的购物车按钮
【发布时间】:2021-12-16 10:05:36
【问题描述】:

如果商品已经在购物车中,我会使用代码更改产品的“添加到购物车”按钮的文本。

/* for single product */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'single_product_button_text' );
 
function single_product_button_text( $text ) {
 
    if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
        $text = 'Product in cart';
    }
 
    return $text;
 
}
 
/* for archive/category pages */
add_filter( 'woocommerce_product_add_to_cart_text', 'products_button_text', 20, 2 );
 
function products_button_text( $text, $product ) {
 
    if( 
       $product->is_type( 'simple' )
       && $product->is_purchasable()
       && $product->is_in_stock()
       && WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
    ) {
 
        $text = 'Product in cart';
 
    }
 
    return $text;
 
}

如果产品已添加到购物车,请告诉我如何更改产品“添加到购物车”按钮的样式?

我尝试将代码添加到 /loop/add-to-cart.php 文件,如此处Change add to cart button style when product is in cart in Woocommerce 所示,但它对我不起作用。

还有其他代码选项可以帮助解决我的问题吗?

我会很高兴得到您的帮助!

【问题讨论】:

    标签: php wordpress woocommerce product


    【解决方案1】:

    一种方法是通过jQuery 检查某个元素(您的添加到购物车按钮)是否包含某个文本,如果是这种情况,我们将添加一个额外的类,您可以通过CSS 设置样式.

    :contains() Selector - 选择所有包含指定文本的元素。

    所以你得到:

    function action_wp_footer() {
        ?>
        <script>
            jQuery(document).ready(function($) {
                var selector = '.add_to_cart_text:contains("Product in cart")';
                
                // Selector contains specific text
                if ( $( selector ).length > 0 ) {
                    $( selector ).addClass( 'product-is-added' );
                } else {
                    $( selector ).removeClass( 'product-is-added' );            
                }
                
            });
        </script>
        <?php
    }
    add_action( 'wp_footer', 'action_wp_footer' );
    

    注意:选择器(类)可以根据您使用的主题命名不同

    【讨论】:

    • 不错的解决方案。恭喜您获得 woocommerce 金色徽章并达到 20k。感谢您与我们分享您的专业知识。我个人从你身上学到了很多。
    • @Ruvee 谢谢。别担心,我也还在学习中。今天看起来不错的代码明天就会过时。尽管我仍然将其作为业余爱好而不是专业人士,但我确实计划开发扩展 WooCommerce 的免费插件。我最近完全从头开始为 WordPress/WooCommerce 编写了我的第一个主题,这很有趣!毕竟,我们来这里是为了互相学习 ;-) 继续努力!
    • 太棒了!我绝对应该尝试那个主题。这个主题应该是一个很棒的主题,我毫不怀疑。如果主题可用,请随时分享主题链接以及准备就绪时的插件。期待尝试所有这些,谢谢,并再次祝贺您取得新成就。
    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2019-10-08
    相关资源
    最近更新 更多