Bruce Banner
Bruce Banner

Reputation: 73

Issue with WooCommerce Product Custom Field value

I am trying to get the value of a custom field so I can compare it to the amount in stock, and display a message depending on the returned value.

I keep being met with boolean false - string length 0 or Uncaught 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;
}

Upvotes: 0

Views: 316

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29650

As I mentioned before, the use of $_REQUEST is not necessary.

In the code below, I set $weight = 40; for testing purposes. Assuming your get_post_meta is correct? and a numerical value?

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

Upvotes: 1

Related Questions