Search code examples
phpwordpresswoocommerceproductcart

Target specific product IDs on WooCommerce cart displayed quantity


I am using this code to make the product show boxes in cart but I just want it to show it on certain products. How can I put the product id?

function cw_change_product_quantity_display( $quantity )  { 
    $quantity .= '  Caja (s)';
    return $quantity;
  }
  add_filter( 'woocommerce_get_quantity_html', 'cw_change_product_quantity_display' );
  add_filter( 'woocommerce_cart_item_quantity', 'cw_change_product_quantity_display' );

Solution

  • The hook woocommerce_get_quantity_html is not defined in WooCommerce core, so maybe it's a custom hook added by a third party plugin, your theme or by yourself…

    Now for the hook woocommerce_cart_item_quantity, there are 2 additional optional arguments missing from your code that will allow you to target a product ID like:

    add_filter( 'woocommerce_cart_item_quantity', 'change_cart_item_displayed_quantity', 10, 3 );
    function change_cart_item_displayed_quantity( $product_quantity, $cart_item_key, $cart_item ) { 
        // Here define your product ID(s) in the array
        $product_ids = array( 37, 53 );
    
        if( array_intersect( [ $cart_item['product_id'], $cart_item['variation_id'] ], $product_ids ) ) {
            $product_quantity .= __('  Caja (s)');
        }
        return $product_quantity;
    }
    

    It should work for some defined product IDs only.

    But as $product quantity is an input number field, your custom text will be display after this quantity field, which is strange.