WooCommerceで商品がカートに入っているときの新しいスタイルのカートボタン

Jan 15 2021

商品がすでにカートに入っている場合、商品の[カートに追加]ボタンのテキストを変更するコードを使用します。

/* 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ファイルにコードを追加しようとしました。Woocommerceで商品がカートに入っているときに[カートに追加]ボタンのスタイルを変更しましたが、機能しません。

私の質問を解決するのに役立つ他のコードオプションはありますか?

よろしくお願いします!

回答

1 7uc1f3r Jan 15 2021 at 15:18

1つの方法はjQuery、特定の要素(カートに追加ボタン)に特定のテキストが含まれているかどうかを確認することです。その場合は、を介してスタイルを設定できるクラスを追加しますCSS

:contains()セレクター-指定されたテキストを含むすべての要素を選択します。

だからあなたは得る:

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' );

注:セレクター(クラス)は、使用しているテーマに応じて異なる名前を付けることができます