I developed a custom delivery time info for variations. But for some reason, I can't get the parent product id of the variation to use it in my function. I tried the following - if I set $id straight to 51237, my code works, but with using $post to get the id, it doesn't. Any help appreciated!
// here I am loading special infos for each variation
add_filter( 'woocommerce_available_variation', 'load_variation_products_fields', 1 );
function load_variation_products_fields( $variations ) {
$variations['variation_cmpzDeliveryTime'] = get_delivery_time( $variations[ 'variation_id' ] ) ;
return $variations;
}
function get_delivery_time ( $product_id) {
$product_obj = wc_get_product( $product_id );
// here I want the post ID (so the parent product ID if the product type is variation)
global $post;
$id = $post->ID;
var_dump ($id); // this outputs "int(51237)" for each variation - that seems to be right!
switch($product_obj->get_type()) {
case 'variation':
if (Helpers::get_product_multi_inventory_status($product_id) == 'no' ) {
$_pf = new WC_Product_Factory();
$_product = $_pf->get_product($product_id);
$stock_status = $_product->get_stock_status();
if ( wc_gzd_get_product( $product_id )->get_delivery_time_html() == '' ) {
if ( ($stock_status == 'instock') ) {
// $id is ignored - if I put here 51237, it works!
return set_delivery_text('instock', $id);
} else {
return set_delivery_text('outofstock');
}
}
}
elseif (Helpers::get_product_multi_inventory_status($product_id) == 'yes' ) {
return get_delivery_time_multi_inventory($product_id);
}
break;
}
}
There are some missing arguments in your function hooked in
woocommerce_available_variation
… You need to replace it by:Now as you can see there is 3 arguments, where
$product
is the parent variable product object and$variation
is the product variation Object.So you will change you will also have to change
get_delivery_time()
function code something like:it should work better.