编程语言
首页 > 编程语言> > php-获取也适用于Woocommerce产品变体的is_purchasable挂钩

php-获取也适用于Woocommerce产品变体的is_purchasable挂钩

作者:互联网

自何时/直到何时,我已经做了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 );

但是变化仍然忽略可用性字段.

解决方法:

对所有产品类型(包括产品变体)尝试以下重新审阅的代码:

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文件中.经过测试和工作.

标签:date-range,woocommerce,product,wordpress,php
来源: https://codeday.me/bug/20191109/2012099.html