Maryna
Maryna

Reputation: 13

WooCommerce checkout page - check if the products are featured

I need your help with the following: on the checkout page of Woocommerce I need to check if added products are featured. If yes then delete some additional fields from the checkout form.

I have tryed the following code but it doesn't work:

add_filter( 'woocommerce_checkout_fields' , 'wc_featured_product_add_checkout_fields' );

function wc_featured_product_add_checkout_fields( $fields ) {
    global $product;

    if ( $product->is_featured() ) {
        unset($fields['billing']['billing_family_name']);
    }
    return $fields;
}

Thanks for your help.

Upvotes: 1

Views: 734

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29614

If a product is featured, remove some additional fields from the checkout form. Comment with explanation added in the code

function wc_featured_product_add_checkout_fields( $fields ) {
    // Set variable
    $found = false;

    // Loop trough cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Is featured
        if ( $product->is_featured() ) {
            $found = true;
            break;
        }
    }

    // True
    if ( $found ) {
        // Unset
        unset( $fields['billing']['billing_first_name'] );
        // Etc..
    }
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'wc_featured_product_add_checkout_fields', 10, 1 );

Upvotes: 1

Related Questions