简体   繁体   中英

Display WooCommerce cart item short description for a specific product categories

In WooCommerce I'm trying to add the product short description for a specific category in the cart items.

I found this code that adds the product short description to ALL products in the cart, but I can't figure out how to narrow it down to only display on specific products:

add_filter('woocommerce_get_item_data', 'wc_checkout_description_so_27900033', 10, 2);

function wc_checkout_description_so_27900033($other_data, $cart_item) {
    $post_data = get_post($cart_item['product_id']);
    echo $post_data - > post_excerpt;
    return $other_data;
}

How can I make this code display the short description only for a defined product category?

Thanks

Update for woocommerce versions 3 and above

I have changed and actualized a little bit your code. Then to target a product category you should usehas_term() conditional WordPress function.

You will have to define in the function your categories IDs, slugs or names.

So here is the code for defined product categories terms:

add_filter('woocommerce_get_item_data', 'filter_woocommerce_get_item_data', 10, 2);
function filter_woocommerce_get_item_data( $item_data, $cart_item ) {

    // Define HERE your Category term IDs, Slugs or Names in the array
    $categories = array('clothing', 'music'); 

    // Product Category condition Below
    if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
        if( ! ( $cart_item['variationt_id'] > 0 ) ) {
            $description = $cart_item['data']->get_short_description();
        } else {
            $description = $cart_item['data']->get_description();
            
            if ( ! empty( $description ) ) {
                $parent_product = wc_get_product( $cart_item['product_id'] );
                $description    = $parent_product->get_short_description();
            }
        }

        if ( ! empty( $description ) ) {
            $item_data[] = array(
               'key'       => __( 'Product description', 'woocommerce' ),
               'value'     => $description,
               'display'   => $description,
            );
        }
    }
    return $item_data;
}

Code goes in functions.php file of your active child theme (or theme) or also in any plugin file.

Code is tested and works.

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