当特定产品类别在 Woocommerce 购物车中时,有条件地应用 CSS 样式

Apply CSS style conditionally when specific product category is in Woocommerce cart

在开始提问之前,我想告诉您我是一名平面设计师,而不是开发人员。我正在帮助一个朋友做他们的网站,所以请原谅我的无知和缺乏知识。

我正在使用 WooCommerce 商店在 Wordpress 中构建网站。我对 CSS 和 HTML 相当满意,但几乎没有 php 知识,而且我对 WooCommerce 还很陌生。

我有一个非常具体的目标想要实现,但我真的不知道从哪里开始。

基本上,我想在将特定类别的产品放入购物车后应用条件 css 样式(如果产品被移除,则反转)。具体来说,我想更改位于小部件中并将显示在 header 上的图标的颜色。所以效果是,当访问者将 'gift' 添加到他们的购物车时,'gift' 图标将 'light up' 提示访问者下一步添加 'card' 等等。

我发现以下内容乍一看可能会让我接近,但我不知道如何实现它,因此非常感谢您的帮助:

// set our flag to be false until we find a product in that category
$cat_check = false;

// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

$product = $cart_item['data'];

// replace 'membership' with your category's slug
if ( has_term( 'membership', 'product_cat', $product->id ) ) {
    $cat_check = true;
    // break because we only need one "true" to matter here
    break;
}
}

// if a product in the cart is in our category, do something
if ( $cat_check ) {
// we have the category, do what we want
}

提前致谢!

在挂钩函数中尝试使用以下略有不同的重新访问代码,这将允许您在购物车项目中找到特定产品类别时添加一些内联 CSS 样式:

add_action( 'wp_head' , 'custom_conditional_css_styles' );
function custom_conditional_css_styles(){
    if( WC()->cart->is_empty() ) return; // We exit is cart is empty

    // HERE your product category
    $product_category = 'membership';
    $found            = false;

    // Loop through cart items checking for our product category
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( has_term( 'membership', 'product_cat', $cart_item['product_id'] ) ) {
            $found = true;
            break; // Found we stop the loop
        }
    }

    if ( ! $found ) return; // If the product category is noy found we exit 

    // Here come your CSS styles
    ?>
    <style>
        .my-class { color:red;}
    </style>
    <?php
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

When using has_term() with cart items, never use $cart_item['data']->get_id() but always $cart_item['product_id'] instead.

假设我们在产品中有两个类别,其中一个类别有 product_cat-slippers class,第二个类别有 product_cat-floaters.

您可以在下面的代码中应用 css with :not selector view。

:not(.product_cat-floaters) {
    color: red;
}

https://www.w3schools.com/cssref/sel_not.asp