带有WooCommerce产品自定义字段值的问题

问题描述 投票:0回答:1

我正在尝试获取自定义字段的值,以便可以将其与库存量进行比较,并根据返回的值显示一条消息。

我一直遇到boolean false-string length 0Uncaught Error: Call to a member function get_meta() on boolean

// check out of stock using 'custom_field' value
    add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_validate_attribute_weight', 10,3);
    function woocommerce_validate_attribute_weight($variation_id, $variations, $product_id) {

    $grams = get_post_meta( $variation_id, 'custom_field', true );

    // 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 variation
    if (isset($_REQUEST["custom_field"])) {
        $weight = preg_replace('/[^0-9.]+/', '', $_REQUEST["custom_field"]);
    } 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;
        }
    }
    var_dump($grams);
    return true;
}
php wordpress woocommerce
1个回答
1
投票

正如我之前提到的,没有必要使用$_REQUEST

在下面的代码中,我设置为$weight = 40;用于测试目的。假设您的get_post_meta是正确的?和一个数值?

function validate_attribute_weight( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // Get custom field
    $weight = get_post_meta( $variation_id, 'custom_field', true );

    // FOR TESTING PURPOSES, DELETE AFTERWORDS!!!
    $weight = 40;
    // FOR TESTING PURPOSES, DELETE AFTERWORDS!!!

    if ( ! empty( $weight ) ) {
        // Get product object
        $product = wc_get_product( $product_id );

        // Get current product stock
        $product_stock = $product->get_stock_quantity();

        // ( Weight * quantity ) > product stock
        if( ( ( $weight * $quantity ) > $product_stock ) ) {
            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_name(), $product_stock ), 'error' );
            $passed = false;
        }
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'validate_attribute_weight', 10, 5 );
© www.soinside.com 2019 - 2024. All rights reserved.