Get is_purchasable hook working for Woocommerce product variations too

百般思念 提交于 2019-12-05 23:34:26

Try this revisited code for all product types (including product variations) :

add_filter( 'woocommerce_is_purchasable', 'purchasable_product_date_range', 20, 2 );
function purchasable_product_date_range( $purchasable, $product ) {
    $date_from = (int) get_post_meta( $product->get_id(), '_availability_schedule_dates_from', true );
    $date_to = (int) get_post_meta( $product->get_id(), '_availability_schedule_dates_to', true );
    if( empty($date_from) ||  empty($date_to) )
        return $purchasable; // Exit (fields are not set)

    $current_date = (int) current_time('timestamp');
    if( ! ( $current_date >= $date_from && $current_date <= $date_to ) )
        $purchasable = false;

    return $purchasable;
}

To make product variation work you need to get the parent product ID, because your variations don't have this date range custom fields:

add_filter( 'woocommerce_variation_is_purchasable', 'purchasable_variation_date_range', 20, 2 );
function purchasable_variation_date_range( $purchasable, $product ) {
    $date_from = (int) get_post_meta( $product->get_parent_id(), '_availability_schedule_dates_from', true );
    $date_to = (int) get_post_meta( $product->get_parent_id(), '_availability_schedule_dates_to', true );
    if( empty($date_from) ||  empty($date_to) )
        return $purchasable; // Exit (fields are not set)

    $current_date = (int) current_time('timestamp');
    if( ! ( $current_date >= $date_from && $current_date <= $date_to ) )
        $purchasable = false;

    return $purchasable;
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!