I have 2 attributes (DiscQuantity, Discount) for all products that have value that I'm going to use later in cart and checkout page to apply discount, these attributes are not assigned for variations I want to get the value in these attributes to pass it to a script that implement the discount The problem is when run this script
add_action( 'woocommerce_cart_calculate_fees', 'progressive_discount_by_item_quantity', 10, 1 );
function progressive_discount_by_item_quantity( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach( $cart_obj->get_cart() as $cart_item_key => $item_values ){
$_product = apply_filters( 'woocommerce_cart_item_product', $item_values['data'] );
$foobar = $_product->get_attribute( 'DiscQuantity' );
?><pre><?php var_dump( $foobar ); ?></pre><?php
}}
//rest of Discount code
var_dump shows this result string(0) ""
I proceed to debug and printed _product in var_dumb it shows only the attributes that are assigned for variations and the two attributes that i need are missing
["attributes"]=>
array(3) {
["pa_size"]=>
string(1) "s"
["pa_color"]=>
string(3) "red"
["pa_fasttrack"]=>
string(6) "normal"
}
my question is how can get these 2 attributes value without assigning them to variations ?
When a cart item is a product variation, you will get the parent variable product object as follows:
add_action( 'woocommerce_cart_calculate_fees', 'progressive_discount_by_item_quantity', 10, 1 );
function progressive_discount_by_item_quantity( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach( $cart->get_cart() as $cart_item ){
// Get the variale product Object when it's a product variation
$product = $cart_item['variation_id'] > 0 ? wc_get_product($cart_item['product_id']) : $cart_item['data'];
$disc_qty = $product->get_attribute( 'DiscQuantity' );
echo '<pre class="custom">'. print_r( $disc_qty, true ) . '</pre>';
}
}
This time you will not get an empty value.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.