How to add custom meta fields to WooCommerce products.

To add custom meta fields in WooCommerce, you typically use hooks to display and save the meta fields. Below is an example of how to add custom meta fields to WooCommerce products.

Add Custom Meta Field to Product Page

Here’s how you can add a custom meta field to the product edit page in the admin area and display/save the value.

1. Add Custom Meta Field to Admin Product Page

Add this code to your theme’s functions.php file or a custom plugin:

// Add a custom meta field to the product edit page
add_action('woocommerce_product_options_general_product_data', 'add_custom_meta_field_to_product');

function add_custom_meta_field_to_product() {
    echo '<div class="options_group">';
    
    woocommerce_wp_text_input(
        array(
            'id'          => '_custom_meta_key',
            'label'       => __('Custom Meta Field', 'woocommerce'),
            'placeholder' => __('Enter your custom value', 'woocommerce'),
            'desc_tip'    => 'true',
            'description' => __('This is a custom meta field for the product.', 'woocommerce'),
        )
    );
    
    echo '</div>';
}

2. Save Custom Meta Field Value

Save the custom meta field value when the product is updated:

add_action('woocommerce_process_product_meta', 'save_custom_meta_field');

function save_custom_meta_field($post_id) {
    $custom_field_value = isset($_POST['_custom_meta_key']) ? sanitize_text_field($_POST['_custom_meta_key']) : '';
    update_post_meta($post_id, '_custom_meta_key', $custom_field_value);
}

3. Display Custom Meta Field on the Product Page

To display the custom meta field on the front end (e.g., single product page), use the following code:

add_action('woocommerce_single_product_summary', 'display_custom_meta_field_on_product_page', 25);

function display_custom_meta_field_on_product_page() {
    global $product;

    $custom_value = get_post_meta($product->get_id(), '_custom_meta_key', true);

    if (!empty($custom_value)) {
        echo '<p class="custom-meta">' . esc_html__('Custom Meta: ', 'woocommerce') . esc_html($custom_value) . '</p>';
    }
}

Notes

  1. Replace '_custom_meta_key' with your actual meta key name.
  2. Use woocommerce_wp_checkbox, woocommerce_wp_select, etc., if you want other types of fields like checkboxes or dropdowns.
  3. For styling or additional functionality, enqueue your custom CSS/JS in the theme or plugin.

Let me know if you need help extending this further!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x