skip to Main Content

I want to hide specific variations from the cart page in Woocommerce, I was able to hide all the variation names but I want to keep 3 that need to be shown. The following code shows all the variations in the cart page, would someone know how to apply a filter in here?

<dl class="variation">
    <?php foreach ( $item_data as $data ) : ?>
        <dt class="<?php echo sanitize_html_class( 'variation-' . $data['key'] ); ?>"><?php echo wp_kses_post( $data['key'] ); ?>: </dt>
        <dd class="<?php echo sanitize_html_class( 'variation-' . $data['key'] ); ?>"><?php echo wp_kses_post( wpautop( $data['display'] ) ); ?></dd>
    <?php endforeach; ?>
</dl>

For example I need to hide one of these:

<dt class="variation-Kcalperdag">Kcal per dag:</dt>
<dd class="variation-Kcalperdag"><p>1641</p> </dd>

2

Answers


  1. You were not that far! You were just missing a simple conditional statement inside that foreach loop. Something like if ( $data['key'] !== 'Kcalperdag' ): should do the trick.
    I’ve tested it with a bogus array and it seems perfect.

    We use the $data['key'] as a condition to chose if we want to display or not our content.

    <dl class="variation">
    <?php
    foreach ( $item_data as $data ):
    if ( $data['key'] !== 'Kcalperdag' ): ?>
      <dt class="<?php echo sanitize_html_class( 'variation-' . $data['key'] ); ?>">
        <?php echo wp_kses_post( $data['key'] ); ?>:
      </dt>
      <dd class="<?php echo sanitize_html_class( 'variation-' . $data['key'] ); ?>">
        <?php echo wp_kses_post( wpautop( $data['display'] ) ); ?>
      </dd>
    <?php endif;
    endforeach; ?>
    </dl>
    
    Login or Signup to reply.
  2. To hide specific(s) product variation attribute(s) displayed in cart (and checkout), you can use dedicated filter hook woocommerce_get_item_data as follows:

    add_filter( 'woocommerce_get_item_data', 'filter_cart_item_data', 10, 2 );
    function filter_cart_item_data( $cart_data, $cart_item ) {
        // Loop through cart item additional displayed data
        foreach ( $cart_data as $key => $values ) {
            // Target "Kcalperdag" attribute from its displayed label name
            if ( $values['key'] === 'Kcal per dag' ) {
                unset($cart_data[$key]); // Remove attribute from the array
            }
        }
    
        return $cart_data;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search