Замените «Атрибут» значением настраиваемого поля (post-meta) в работающем скрипте (Woocommerce) - PullRequest
0 голосов
/ 03 апреля 2020

Это должно быть довольно просто, но я продолжаю получать «Внутреннюю ошибку сервера» при попытке заменить значение настраиваемого поля на значение атрибута.

Ниже у меня есть 2 рабочие функции ...

  1. Первая - это функция, которая добавляет настраиваемое поле в переменный продукт (и отображает его значение / информацию во внешнем интерфейсе).

  2. Вторая вычитает сумму из общего запаса Переменного продукта, используя числовое значение c атрибута.

**

Я бы хотел использовать значение цифры 1041 * из моего настраиваемого поля, а не атрибута.

**

// -----------------------------------------
// 1. Add custom field input @ Product Data > Variations > Single Variation

add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 );

function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Amount of Product', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
)
);
}

// -----------------------------------------
// 2. Save custom field on product variation save

add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );

function bbloomer_save_custom_field_variations( $variation_id, $i ) {
$custom_field = $_POST['custom_field'][$i];
if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
}

// -----------------------------------------
// 3. Store custom field value into variation data

add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );

function bbloomer_add_custom_field_variation_data( $variations ) {
$variations['custom_field'] = '<div class="woocommerce_custom_field">Amount: <span class="weight">' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
return $variations;
}

НИЖЕ СЦЕНАРИЙ ДЛЯ ВЫЧИСЛЕНИЯ СУММ, ОСНОВАННЫХ НА АТРИБУТЕ

// reduce stock based on 'pa_weight' attribute
add_filter( 'woocommerce_order_item_quantity', 'filter_order_item_quantity', 10, 3 ); 
function filter_order_item_quantity( $quantity, $order, $item )  
{
    $product   = $item->get_product();
    $term_name = $product->get_attribute('pa_weight');

    // 'pa_weight' attribute value is "15 grams" - keep only the numbers
    $quantity_grams = preg_replace('/[^0-9.]+/', '', $term_name);

    // new quantity
    if( is_numeric ( $quantity_grams ) && $quantity_grams != 0 )
        $quantity *= $quantity_grams;

    return $quantity;
}

// check out of stock using 'pa_weight' attribute
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_validate_attribute_weight' );
function woocommerce_validate_attribute_weight() 
{
    // get product id
    if (isset($_REQUEST["add-to-cart"])) {
        $productid = (int)$_REQUEST["add-to-cart"];
    } else {
        $productid = null;
    }

    // get quantity
    if (isset($_REQUEST["quantity"])) {
        $quantity = (int)$_REQUEST["quantity"];
    } else {
        $quantity = 1;
    }

    // get weight of selected attribute
    if (isset($_REQUEST["attribute_pa_weight"])) {
        $weight = preg_replace('/[^0-9.]+/', '', $_REQUEST["attribute_pa_weight"]);
    } else {
        $weight = null;
    }

    // comparing stock
    if($productid && $weight)
    {
        $product = wc_get_product($productid);
        $productstock = (int)$product->get_stock_quantity();

        if(($weight * $quantity) > $productstock)
        {
            wc_add_notice( sprintf( 'You cannot add that amount of "%1$s" to the cart because there is not enough stock (%2$s remaining).', $product->get_title(), $productstock ), 'error' );
            return;
        }
    }

    return true;
}

Я попытался заменить:

$term_name = $product->get_attribute('pa_weight');

на:

$term_name = $product->get_post_meta('custom_field');

Это не сработало ... Не уверен, где проблема.

1 Ответ

0 голосов
/ 03 апреля 2020

woocommerce_add_to_cart_validation содержит 5 параметров (последние 2 являются необязательными)

$passed = по умолчанию возвращает true

$product_id = идентификатор продукта, это дает вам доступ к wc_get_product( $product_id ) для получения объекта продукта

$quantity = текущее количество, которое вы хотите добавить в корзину

Таким образом, использование isset($_REQUEST[]) вообще не нужно

function woocommerce_validate_attribute_weight( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // Get product object
    $product = wc_get_product( $product_id );

    if( $quantity > 10 ) {
        wc_add_notice( __( 'Limit is 10', 'woocommerce' ), 'error' );
        $passed = false;
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_validate_attribute_weight', 10, 5 );

Убедитесь, что при написании кода включена поддержка отчетов об ошибках, это уже решит многие проблемы или хотя бы уточнить, как указано @ simong cc

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...