0

I am trying to retrieve post id under custom_fields_validation() function but I am receiving the following

error: Trying to get property of non-object on line 116

add_action('woocommerce_add_to_cart_validation','custom_fields_validation'), 10, 3 );



public static function custom_fields_validation() 
    { 

    global $post;

if(isRecurring($post->ID)){
if ( empty( $_POST['inputday']) ){
            wc_add_notice( __( 'Please select field 1;', 'woocommerce' ), 'error' );
            return false; 
        }
        if ( empty( $_POST['inputtime'] )){
            wc_add_notice( __( 'Please select field 2;', 'woocommerce' ), 'error' );
            return false; 
        }
}           
    return true;
    }
0

woocommerce_add_to_cart_validation passes the product id as the second argument to the callback function, so you can access it like this:

function custom_fields_validation( $passed_validation, $product_id ) { 
    if( isRecurring( $product_id ) ) {
        if ( empty( $_POST['inputday']) ){
            wc_add_notice( __( 'Please select field 1;', 'woocommerce' ), 'error' );
            return false; 
        }
        if ( empty( $_POST['inputtime'] )){
            wc_add_notice( __( 'Please select field 2;', 'woocommerce' ), 'error' );
            return false; 
        }
    }

    return $passed_validation;
}
add_filter( 'woocommerce_add_to_cart_validation', 'custom_fields_validation', 10, 2 );

Also, note that woocommerce_add_to_cart_validation is a filter, not an action, so I've used apply_filters instead of add_action. I also fixed a syntax error, where you had an extra parentheses after 'custom_fields_validation'.

I also updated the function to return the current validation state. Otherwise you could be returning true even if a previous validation had failed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.