简体   繁体   中英

Add product id to cart item class

I want to get the product_id for an item in cart and then echo it to a class (custom id ), so I can style items individually.

I have this:

<?php
    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id'];
        break;
    }
    $product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
?> 

<li id="mcitem-<?php echo esc_attr($cart_item_key); ?>" class="custom-<?php echo $product_id'; ?>">

This part was already in the mini-cart.php template, and so was the li but without the class attribute, which I added.

$product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

I tried to echo $product_id in different ways inside the class:

echo '$product_id';
echo esc_attr($product_id);

Tested both and didn't work. Then I found this snippet:

foreach( WC()->cart->get_cart() as $cart_item ){
    $product_id = $cart_item['product_id'];
    break;
}

(also tested it without the break, so it has been tested inside and outside of loop)

Then I repeated the two echos, but still blank echo result (none).

What am I doing wrong here?

If you want to add a class to the cart row, you can filter woocommerce_cart_item_class .

/**
 * Changes the tr class of cart items.
 *
 * @param  string  $class
 * @param  array   $values
 * @param  string  $values_key
 * @return string
 */
function so_42237701_cart_item_class( $class, $values, $values_key ) {

    if ( isset( $values[ 'product_id' ] ) ) {
        $class .= ' custom-' . $values[ 'product_id' ];
    }

    return $class;
}
add_filter( 'woocommerce_cart_item_class', 'so_42237701_cart_item_class', 10, 3 );

And for the mini cart:

/**
 * Changes the tr class of items in the mini-cart.
 *
 * @param  string  $class
 * @param  array   $values
 * @param  string  $values_key
 * @return string
 */
function so_42237701_mini_cart_item_class( $class, $cart_item, $cart_item_key ) {

    if ( isset( $cart_item[ 'product_id' ] ) ) {
        $class .= ' custom-' . $cart_item[ 'product_id' ];
    }

    return $class;
}
add_filter( 'woocommerce_mini_cart_item_class', 'so_42237701_mini_cart_item_class', 10, 3 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM