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

WordPress / 10 MIN READ

PHP Import Custom Woo

Importing custom fields into WooCommerce

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

Certainly! Below is a comprehensive step-by-step tutorial to help you import CSV files with custom fields into WooCommerce and display those custom fields on your product pages. This guide integrates all the code snippets you’ve provided and ensures a seamless workflow from importing data to displaying it on the frontend.


Tutorial: Importing and Displaying Custom Fields in WooCommerce

Overview

This tutorial will guide you through:

  1. Preparing Your CSV File with custom fields.
  2. Adding Custom Fields to the WooCommerce Importer.
  3. Importing the CSV into WooCommerce.
  4. Displaying Custom Fields on Product Pages.
  5. Testing Your Implementation.

Prerequisites

  • A WordPress website with WooCommerce installed and activated.
  • Access to your theme’s functions.php file or the ability to add custom code via a plugin like Code Snippets.
  • Basic understanding of PHP and WordPress hooks.

Step 1: Prepare Your CSV File with Custom Fields

To import custom fields, your CSV file must include columns that correspond to the custom meta keys in WooCommerce.

Example CSV Structure:

SKU Name Price _andover_wavelength_value
12345 Red Laser 199.99 650 nm
67890 Green Laser 249.99 532 nm

Important:

  • The column header for your custom field must exactly match the meta key (_andover_wavelength_value), including the underscores and case sensitivity.
  • Alternatively, you can use a human-readable label (e.g., “Andover Wavelength Value”) and map it programmatically (covered in later steps).

Step 2: Add Code to Handle Custom Field Import

To ensure WooCommerce recognizes and imports your custom fields, you’ll need to add specific code to your theme’s functions.php file or via a plugin like Code Snippets.

Complete Code Snippet:

<?php
// 1. Register the custom field in the WooCommerce CSV importer
add_filter('woocommerce_product_importer_parsed_data', 'add_custom_field_to_importer', 10, 2);
add_filter('woocommerce_csv_product_import_mapping_options', 'add_custom_field_to_mapping');
add_filter('woocommerce_csv_product_import_mapping_default_columns', 'map_custom_field_column', 10, 2);

// Function to add custom field to importer parsed data
function add_custom_field_to_importer($parsed_data, $importer) {
    if (!empty($parsed_data['_andover_wavelength_value'])) {
        $parsed_data['meta_data'][] = array(
            'key'   => '_andover_wavelength_value',
            'value' => $parsed_data['_andover_wavelength_value'],
        );
    }
    return $parsed_data;
}

// Function to add custom field to import mapping options
function add_custom_field_to_mapping($options) {
    $options['_andover_wavelength_value'] = 'Andover Wavelength Value';
    return $options;
}

// Function to map custom field column automatically
function map_custom_field_column($columns, $column_name) {
    if ($column_name === 'Andover Wavelength Value') {
        $columns['_andover_wavelength_value'] = 'Andover Wavelength Value';
    }
    return $columns;
}

// 2. Handle the custom field during product import
add_action('woocommerce_product_import_inserted_product_object', 'add_custom_field', 10, 2);

function add_custom_field($product, $data) {
    if (!empty($data['_andover_wavelength_value'])) {
        $product->update_meta_data('_andover_wavelength_value', $data['_andover_wavelength_value']);
    }
}

// 3. Create a shortcode to display the custom field
add_shortcode('display_wavelength', 'display_wavelength_shortcode');

function display_wavelength_shortcode() {
    global $post;

    // Fetch the custom field value
    $wavelength = get_post_meta($post->ID, '_andover_wavelength_value', true);

    // Output the value or a default message
    if (!empty($wavelength)) {
        return '<div class="custom-field"><strong>Wavelength:</strong> ' . esc_html($wavelength) . '</div>';
    } else {
        return '<div class="custom-field"><strong>Wavelength:</strong> Not available</div>';
    }
}

// 4. Enqueue custom scripts if needed (optional)
add_action('wp_enqueue_scripts', 'enqueue_csv_chart_script');

function enqueue_csv_chart_script() {
    wp_enqueue_script(
        'csv-chart-script', // Unique handle for the script
        get_template_directory_uri() . '/js/path-to-script.js', // Path to your JS file
        array('jquery'), // Dependencies
        '1.0.0', // Version
        true // Load in the footer
    );
}
?>

Explanation of the Code:

  1. Registering the Custom Field for Import:

    • Filters are added to include _andover_wavelength_value in the import process.
    • The custom field is labeled as “Andover Wavelength Value” for easy identification during import.
  2. Handling the Custom Field During Import:

    • The add_custom_field function ensures that the custom field data from the CSV is saved to the product’s meta data.
  3. Creating a Shortcode to Display the Custom Field:

    • The [display_wavelength] shortcode can be used anywhere on your site to display the wavelength value of a product.
  4. Enqueueing Custom Scripts (Optional):

    • If you have custom JavaScript (e.g., for handling CSV charts), enqueue it using enqueue_csv_chart_script.

How to Add the Code:

  • Via Theme’s functions.php:

    • Navigate to Appearance > Theme Editor in your WordPress dashboard.
    • Select functions.php from the list of theme files.
    • Caution: Editing functions.php directly can break your site if there’s a syntax error. It’s recommended to use a child theme or a plugin like Code Snippets for safer code management.
  • Via Code Snippets Plugin:

    • Install and activate the Code Snippets plugin.
    • Go to Snippets > Add New.
    • Paste the entire code snippet above.
    • Give it a descriptive name (e.g., “WooCommerce Custom Field Import and Display”) and save.

Step 3: Import the CSV into WooCommerce

Now that you’ve set up the importer to handle custom fields, you can proceed to import your CSV.

Steps to Import:

  1. Navigate to WooCommerce Products Importer:

    • Go to WooCommerce > Products.
    • Click the Import button at the top.
  2. Upload Your CSV File:

    • Click Choose File and select your prepared CSV file.
    • Click Continue.
  3. Mapping Columns:

    • The importer will attempt to automatically map columns based on headers.
    • Custom Field Mapping:
      • Ensure that your custom field (_andover_wavelength_value or “Andover Wavelength Value”) appears in the list.
      • If you used the human-readable label (“Andover Wavelength Value”), it should be automatically mapped to _andover_wavelength_value based on the code you added.
    • Verify Mappings:
      • Check that each column is correctly mapped to the corresponding WooCommerce field or custom field.
    • Click Run the Importer to start the import process.
  4. Completion:

    • Once the import is complete, you’ll receive a confirmation message.
    • Navigate to Products > All Products to verify that the products have been imported with the custom field data.

Step 4: Displaying Custom Fields on Product Pages

You have multiple options to display the custom field (_andover_wavelength_value) on your product pages. Below are two primary methods:

Option 1: Using a Shortcode

The code snippet provided earlier includes a shortcode [display_wavelength] that you can use anywhere on your product pages.

How to Use:

  1. Edit a Product:

    • Go to Products > All Products.
    • Click Edit on a product where you want to display the wavelength.
  2. Insert the Shortcode:

    • In the product description or any other content area, add the shortcode:
      [display_wavelength]
      
    • Update the product to save changes.
  3. View the Product Page:

    • Visit the product page on the frontend to see the custom field displayed.

Example Output:

<div class="custom-field">
    <strong>Wavelength:</strong> 650 nm
</div>

Styling the Shortcode Output:

Add the following CSS to your theme’s style.css or via the WordPress Customizer (Appearance > Customize > Additional CSS):

.custom-field {
    margin-top: 20px;
    font-size: 16px;
    background-color: #f9f9f9;
    padding: 10px;
    border-left: 4px solid #007cba; /* WooCommerce blue */
}

.custom-field strong {
    color: #333;
}

Option 2: Automatically Displaying via WooCommerce Hooks

For a more integrated approach, you can automatically display the custom field on all product pages without manually adding shortcodes.

Add the Following Code to functions.php or Code Snippets:

<?php
// Automatically display the custom field on single product pages
add_action('woocommerce_single_product_summary', 'display_custom_field_on_product_page', 25);

function display_custom_field_on_product_page() {
    global $post;

    // Fetch the custom field value
    $wavelength = get_post_meta($post->ID, '_andover_wavelength_value', true);

    // Check if the custom field has a value, then display it
    if (!empty($wavelength)) {
        echo '<div class="custom-field">';
        echo '<p><strong>Wavelength:</strong> ' . esc_html($wavelength) . '</p>';
        echo '</div>';
    }
}
?>

Explanation:

  • Hook: woocommerce_single_product_summary is used to insert content into the single product summary area.
  • Priority 25: Determines the placement relative to other elements. You can adjust this number to move the custom field up or down the order.

Styling:

Use the same CSS as provided in Option 1 to style the output.


Step 5: Testing Your Implementation

After setting up the import and display mechanisms, it’s crucial to test everything to ensure it works as expected.

1. Verify Imported Data:

  • In WooCommerce Admin:

    • Go to Products > All Products.
    • Edit a product and scroll down to the Custom Fields section.
    • Ensure that _andover_wavelength_value is present with the correct value.
  • In the Database (Optional):

    • Use a tool like phpMyAdmin to check the wp_postmeta table.
    • Verify that the meta key _andover_wavelength_value is associated with the correct post_id.

2. Verify Frontend Display:

  • Shortcode Method:

    • Visit a product page where you added the [display_wavelength] shortcode.
    • Ensure that the wavelength is displayed correctly.
  • Hook Method:

    • Visit any product page and verify that the wavelength appears automatically in the designated area.

3. Handle Missing Data:

  • Products without the _andover_wavelength_value should either not display the custom field or show a default message like “Not available,” depending on your implementation.

Optional Enhancements

1. Making the Label Configurable

Instead of hardcoding the label “Wavelength,” you can make it dynamic to support multiple labels in different contexts.

Add to functions.php or Code Snippets:

<?php
// Function to retrieve custom field labels
function get_custom_field_label($key) {
    $labels = [
        '_andover_wavelength_value' => 'Wavelength',
        // Add more custom fields and their labels here
    ];

    return isset($labels[$key]) ? $labels[$key] : '';
}

// Modify the display function to use dynamic labels
add_action('woocommerce_single_product_summary', 'display_custom_field_on_product_page', 25);

function display_custom_field_on_product_page() {
    global $post;

    // Define the meta key
    $meta_key = '_andover_wavelength_value';

    // Fetch the custom field value
    $wavelength = get_post_meta($post->ID, $meta_key, true);

    // Get the dynamic label
    $label = get_custom_field_label($meta_key);

    // Check if both label and value exist, then display
    if (!empty($wavelength) && !empty($label)) {
        echo '<div class="custom-field">';
        echo '<p><strong>' . esc_html($label) . ':</strong> ' . esc_html($wavelength) . '</p>';
        echo '</div>';
    }
}
?>

Benefits:

  • Scalability: Easily add more custom fields by updating the $labels array.
  • Flexibility: Change labels without modifying multiple code sections.

2. Using Beaver Builder for Displaying Custom Fields

If you prefer a visual approach to designing your product pages, integrating with Beaver Builder can be advantageous.

Steps:

  1. Install Beaver Builder and Beaver Themer:

    • Purchase and install Beaver Builder and the Beaver Themer add-on.
    • Activate both plugins.
  2. Enable WooCommerce Modules:

    • Go to Settings > Beaver Builder > Modules.
    • Enable WooCommerce Modules.
  3. Create a Custom Single Product Template:

    • Navigate to Beaver Builder > Themer Layouts.
    • Click Add New and select Single Product as the layout type.
    • Design your product page using Beaver Builder’s drag-and-drop interface.
    • Use Dynamic Content features to pull in custom fields like _andover_wavelength_value.
  4. Add the Custom Field to the Design:

    • Use the Text Editor module.
    • Click on Dynamic Content and select Custom Field.
    • Enter the meta key _andover_wavelength_value.
    • Style as desired.
  5. Publish the Template:

    • Set the Display Conditions (e.g., All Products, Specific Categories).
    • Save and publish your custom template.

Benefits:

  • Visual Design: No need to write PHP code for layout.
  • Reusable Templates: Apply the same design across multiple products or categories.

Troubleshooting Tips

  1. Custom Fields Not Importing:

    • Check CSV Headers: Ensure the custom field column matches the meta key or the human-readable label defined in your code.
    • Verify Import Mapping: During import, confirm that the custom field is correctly mapped.
    • Inspect wp_postmeta: Use phpMyAdmin to check if the custom field data exists.
  2. Custom Fields Not Displaying:

    • Ensure Correct Hook Usage: Verify that the hook (woocommerce_single_product_summary) is correctly implemented.
    • Check for Code Errors: Syntax errors in functions.php can prevent code execution. Use a code editor or enable WP_DEBUG to spot issues.
    • Review Shortcode Usage: Ensure the [display_wavelength] shortcode is correctly placed in the content.
  3. Styling Issues:

    • CSS Conflicts: Other CSS rules might override your custom styles. Use browser developer tools to inspect and adjust as needed.
    • Cache Problems: Clear any caching plugins or browser caches to see the latest changes.
  4. Import Process Skipping Custom Fields:

    • Ensure Hooks Are Active: Make sure the code handling custom fields is active and not conflicting with other plugins.
    • Use Advanced Import Plugins: If WooCommerce’s built-in importer is insufficient, consider plugins like WP All Import for more control.

Conclusion

By following this tutorial, you’ve successfully:

  • Prepared a CSV file with custom fields for WooCommerce products.
  • Extended WooCommerce’s importer to recognize and handle custom fields.
  • Displayed custom fields on your product pages using both shortcodes and hooks.
  • Optionally enhanced the display with dynamic labels and integrated with Beaver Builder for a visual design approach.

This setup not only streamlines your product management process but also enriches your store’s frontend with valuable product information, enhancing the user experience.


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