获得is_purchasable钩子也适用于Woocommerce产品变种

时间:2018-03-25 08:22:14

标签: php wordpress woocommerce product date-range

我已经制作了2个自定义产品字段 - 可用性 - 从何时/直到何时。因此,如果当前日期在这些设定的可用日期之间,那么产品是可购买的,否则 - 它不是。一切都很完美,但只有在我发布带有变化的产品之后。然后,就像产品变体忽略这些自定义可用性字段/值一样,即使当前日期不在设置的可用日期之间,仍然可以向购物车添加变体。

function hide_product_if_unavailable( $is_purchasable, $object ) {

  $date_from = get_post_meta( $object->get_id(), '_availability_schedule_dates_from' );
  $date_to = get_post_meta( $object->get_id(), '_availability_schedule_dates_to' );
  $current_date = current_time('timestamp');

  if ( strlen($date_from[0]) !== 0 ) {

    if ( ( $current_date >= (int)$date_from[0] ) && ( $current_date <= (int)$date_to[0] ) ) {

      return true;

    } else {

      return false;

    }

  } else {

    # Let adding product to cart if Availability fields was not set at all
    return true;

  }

}
add_filter( 'woocommerce_is_purchasable', 'hide_product_if_unavailable', 10, 2 );

我尝试在woocommerce_is_purchasable下面添加另一个过滤器:

add_filter( 'woocommerce_variation_is_purchasable', 'hide_product_if_unavailable', 10, 2 );

但变体仍然会忽略可用性字段。

1 个答案:

答案 0 :(得分:3)

针对所有产品类型(包括产品变体)尝试此重新访问的代码:

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;
}

要使产品差异工作,您需要父产品ID ,因为您的变体不具有此日期范围自定义字段:

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;
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。

相关问题