Get value of the Custom Field on a Woocommerce Product Variation


I really need some help here. 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.

The problem? No matter what I try I keep being met with boolean falsestring length 0 or Uncaught Error: Call to a member function get_meta() on boolean

Please for the love of god, how can I get the value of this custom field that is stored in the meta information of that product’s variation?

I’ve been trying for 2 days without luck! I will love you forever!

// 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 true;
, , Bruce Banner 3 years 2020-04-06T00:50:57-05:00 0 Answers 81 views 0

Leave an answer