0

I have a custom field, 'woocommerce_product_rate' for a woocommerce product intended to be added after the quantity input field, so instead of just displaying, for example, "10", it can display "10 Bananas". I'm trying to retrieve the product ID within quantity-input.php, but am having difficultly. I tried accessing it through the "$product" global using $product->get_the_id(), but that renders a php error. Trying to access the $post global doesn't work either.

/**
* Product quantity inputs
*/

global $product;
$id = $product->get_id();
$unit = get_field('woocommerce_product_rate', $id);
<?php if( $unit !== '') {echo $unit . " ";} ?>

Any suggestions on how to get around this problem would be greatly appreciated, thank you.

DanL
  • 91
  • 1
  • 9

2 Answers2

1

Direct global $product or global $post won't work in global templates. You would need to pass product id as a parameter from woocommerce/cart/cart.php file, where it is adding the filter:

$product_quantity = woocommerce_quantity_input( array(
                                'input_name'   => "cart[{$cart_item_key}][qty]",
                                'input_value'  => $cart_item['quantity'],
                                'max_value'    => $_product->get_max_purchase_quantity(),
                                'min_value'    => '0',
                                'product_name' => $_product->get_name(),
                                'product_id' => $product_id
                            ), $_product, false );

echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );

And then product id would be accessible the in global template, In your case woocommerce/cart/quantity-input.php you can access product id using $args['product_id']

1

I found out that you can modify the quantity input args using a filter woocommerce_quantity_input_args:

<?php 

add_filter("woocommerce_quantity_input_args", function ($args, $product) {
    if (!empty($product)) {
        $args["product_id"] = $product->get_id();
    }
    return $args;
}, 10, 2);

After that you should have $args["product_id"] defined even in the cart when using the template file quantity-input.php.

Ciantic
  • 6,064
  • 4
  • 54
  • 49