fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← WordPress

WordPress / 8 MIN READ

Woo Custom Fields 101

Introduction to WooCommerce custom fields

From the original Fervor library. Examples may use older package versions.

How to Add Custom Fields in WooCommerce (e.g., _andover_wavelength_value)

Custom fields, also called meta fields, are extra data fields you can attach to products in WooCommerce. They’re perfect for storing unique attributes like wavelengths, dimensions, or any custom data your products need. Let’s explore how to add and manage a custom field like _andover_wavelength_value step-by-step.


1. Understanding Custom Fields in WooCommerce

  • What Are Custom Fields? Custom fields store metadata—extra information about a product. For example:

    • _andover_wavelength_value: Stores the wavelength (e.g., 650 nm).
    • _custom_shipping_time: Stores custom shipping times (e.g., 5 days).
  • How Are They Used?

    • Custom fields are often used by themes or plugins to display extra information on product pages.
    • They can be accessed programmatically using WooCommerce’s APIs.

2. Enabling Custom Fields for Testing

Before adding custom fields programmatically, you may want to test them manually.

  1. Enable Custom Fields Display

    • Go to the WordPress Admin Dashboard.
    • Navigate to Products > Edit Product.
    • In the product editing screen, click Screen Options (top-right corner).
    • Check the box for Custom Fields.
  2. Manually Add a Custom Field

    • Scroll down to the Custom Fields section on the product editing screen.
    • Click Add Custom Field:
      • Enter _andover_wavelength_value as the field name.
      • Enter a value, such as 650 nm.
    • Save or update the product.

3. Adding Custom Fields Programmatically

To streamline custom field management, especially during imports, you can add custom fields automatically using WooCommerce hooks.

Step 1: Add Code to Your Theme’s functions.php File

  1. Open your WordPress installation’s theme directory.

    • Go to: wp-content/themes/your-active-theme/.
    • Locate the functions.php file.
  2. Add the following code snippet to handle the _andover_wavelength_value custom field during imports:

    add_action('woocommerce_product_import_inserted_product_object', 'add_custom_field', 10, 2);
    
    function add_custom_field($product, $data) {
        // Check if the custom field exists in the import data
        if (!empty($data['_andover_wavelength_value'])) {
            // Add or update the custom field for the product
            $product->update_meta_data('_andover_wavelength_value', $data['_andover_wavelength_value']);
        }
    }
    
    • What This Does:
      • Hooks into WooCommerce’s product import process.
      • Looks for _andover_wavelength_value in the import data.
      • Adds it as a custom field for the product if it exists.

Step 2: Save and Test

  • Save the functions.php file.
  • Perform a product import with a CSV that includes the _andover_wavelength_value field.
  • The custom field should now appear for imported products.

4. Viewing Custom Fields After Import

  1. Check Custom Fields in the Product Edit Screen

    • Go to Products > Edit Product.
    • Scroll to the Custom Fields section.
    • You should see _andover_wavelength_value listed with its corresponding value.
  2. Check in the Database (Optional)

    • If you’re comfortable working with databases, verify the custom field in the wp_postmeta table:
      • Field: _andover_wavelength_value.
      • Associated with the product’s post ID.

5. Displaying Custom Fields on the Frontend

To show the custom field (e.g., _andover_wavelength_value) on the product page:

Method 1: Using Code

Edit your theme’s single-product.php template to display the custom field:

<?php
// Get the custom field value
$wavelength = get_post_meta(get_the_ID(), '_andover_wavelength_value', true);

// Display it if it exists
if ($wavelength) {
    echo '<p>Wavelength: ' . esc_html($wavelength) . '</p>';
}
?>
  • Place this code where you want the wavelength to appear (e.g., below the product title).

Method 2: Using a Page Builder or Plugin

  • If you use a page builder like Elementor or plugins like Advanced Custom Fields (ACF):
    • Create a dynamic field for _andover_wavelength_value.
    • Drag and drop it into your product page design.

6. Testing and Debugging

  1. Test Your Imports:

    • Import a CSV with products that include _andover_wavelength_value.
    • Example CSV:
      SKU Name _andover_wavelength_value
      12345 Red Laser 650 nm
      67890 Green Laser 532 nm
  2. Debugging Issues:

    • If the custom field isn’t appearing, ensure:
      • The CSV column matches _andover_wavelength_value.
      • The functions.php code is correctly added.
    • Check error logs for clues.

Summary

  • Manually Test: Enable custom fields in the WordPress editor.
  • Automate Imports: Use WooCommerce hooks to handle custom fields like _andover_wavelength_value during CSV imports.
  • Frontend Display: Customize templates or use plugins to show the field on product pages.

BONUS: A Deep Dive into WooCommerce Custom Fields

Let’s fully unpack everything you need to know about WooCommerce custom fields, with practical examples, use cases, and tips to implement them effectively. 🌟


What Are Custom Fields (Meta Fields) in WooCommerce?

Core Idea:

  • Custom fields allow you to store additional information for WooCommerce products, customers, or orders.
  • In technical terms, they are metadata—data about data—that WordPress and WooCommerce store in the wp_postmeta table.

How They Work:

  • Each product is a post in WordPress. Custom fields are like extra sticky notes attached to those posts.
  • For example:
    • Field: _andover_wavelength_value
    • Value: 650 nm
  • These fields can be added manually, during imports, or programmatically.

How WooCommerce Uses Custom Fields

WooCommerce uses built-in custom fields for product attributes like SKU, weight, or dimensions. When you add your custom field, you’re essentially expanding this capability. Examples include:

  • Technical Specs: _andover_wavelength_value, _custom_voltage.
  • Special Offers: _custom_discount_label (e.g., “Buy One Get One Free”).
  • Product Identifiers: _product_internal_id (for linking to external systems).

Step-by-Step Tutorial for Adding and Using Custom Fields

1. Adding Custom Fields via the WordPress Editor

This is the easiest way to start with custom fields, suitable for testing or small tweaks.

Steps:

  1. Go to Products in your WordPress Admin Dashboard.
  2. Edit a product.
  3. Open Screen Options at the top right and check the box for Custom Fields.
  4. Scroll down to the Custom Fields section.
    • Click Add Custom Field.
    • Name the field _andover_wavelength_value.
    • Set its value (e.g., 650 nm).
  5. Update the product.

Limitations:

  • This method is manual and time-consuming for bulk edits.
  • Custom fields added this way are not automatically displayed on the frontend.

2. Bulk Importing Custom Fields via CSV

Why Import?

If you have many products to update, importing custom fields saves you from adding them one by one.

Steps:

  1. Prepare a CSV file:

    • Include a column for your custom field, like _andover_wavelength_value.
      SKU Name _andover_wavelength_value
      12345 Red Laser 650 nm
      67890 Green Laser 532 nm
  2. Import the CSV:

    • Use WooCommerce’s built-in Product Importer or a plugin like WP All Import.
    • During mapping:
      • Map _andover_wavelength_value to a custom meta field.
  3. Verify the import:

    • Check Products > Edit Product.
    • Ensure _andover_wavelength_value is visible in the custom fields.

3. Adding Custom Fields Programmatically

For more advanced use cases, or when importing data, you’ll want WooCommerce to recognize and process your custom fields automatically.

How It Works:

You’ll use WordPress and WooCommerce hooks in your theme’s functions.php file.

Code Example:

Here’s a breakdown of how to automatically save _andover_wavelength_value during product imports:

// Hook into the product import process
add_action('woocommerce_product_import_inserted_product_object', 'add_custom_field', 10, 2);

function add_custom_field($product, $data) {
    // Check if the import data includes the custom field
    if (!empty($data['_andover_wavelength_value'])) {
        // Add or update the custom field for this product
        $product->update_meta_data('_andover_wavelength_value', $data['_andover_wavelength_value']);
    }
}

What This Does:

  1. Runs every time a product is imported or updated.
  2. Checks if _andover_wavelength_value exists in the import data.
  3. Saves the value as metadata for the product.

Where to Place This Code:

  • Add it to your theme’s functions.php file.
  • Use a child theme to avoid losing changes during theme updates.

4. Displaying Custom Fields on the Frontend

Once custom fields are added, you can display them on product pages. Here’s how:

Method 1: Using Code

Modify the product template file (single-product.php) to include your custom field.

<?php
// Fetch the custom field value
$wavelength = get_post_meta(get_the_ID(), '_andover_wavelength_value', true);

// Display the value if it exists
if ($wavelength) {
    echo '<p><strong>Wavelength:</strong> ' . esc_html($wavelength) . '</p>';
}
?>

Method 2: Using a Plugin

If you’re not comfortable editing theme files:

  • Install a plugin like Advanced Custom Fields (ACF) or Custom Product Tabs for WooCommerce.
  • Use their interface to dynamically display custom fields.

Testing the Frontend Display:

  • Open the product page on your site.
  • Confirm the wavelength (or any custom field value) is displayed as expected.

Advanced Tips and Use Cases

  1. Using Custom Fields in WooCommerce Filters:

    • You can enable advanced product filtering using plugins like FacetWP or Filter Everything to create filters based on _andover_wavelength_value.
  2. Searchable Custom Fields:

    • Make custom fields searchable by hooking into WordPress queries or using a plugin like SearchWP.
  3. WooCommerce REST API Integration:

    • Fetch or update custom fields programmatically via WooCommerce’s REST API:
      $product = wc_get_product($product_id);
      $wavelength = $product->get_meta('_andover_wavelength_value');
      
  4. Dynamic Pricing or Rules:

    • Use custom fields to create dynamic pricing rules. For example, change the price based on _andover_wavelength_value.

Troubleshooting Common Issues

  1. Custom Fields Not Showing on Product Pages:

    • Ensure your code in single-product.php is placed correctly.
    • Verify the custom field exists using the Products > Edit Product screen.
  2. Fields Not Imported Correctly:

    • Double-check your CSV formatting.
    • Make sure your field names match exactly (_andover_wavelength_value).
  3. Functions.php Errors:

    • Use a PHP linter to check for syntax errors.
    • If the site breaks, check your server error logs or disable the code temporarily.

When to Use Custom Fields

Custom fields are ideal when:

  • You need to store unique, per-product data.
  • The data isn’t part of WooCommerce’s default fields.
  • You want flexibility in how the data is displayed or used (e.g., for filters, dynamic rules, or APIs).

Conclusion

Custom fields in WooCommerce, like _andover_wavelength_value, are powerful tools for tailoring your store to specific needs. By combining manual edits, bulk imports, and programmatic automation, you can easily scale your product management while maintaining a seamless customer experience.

Keep your curiosity going.Explore more WordPress →
287 TUTORIALS · 22 TOPICSREADY