Categories
WooCommerce

Adding custom fields (metadata) to WooCommerce product attributes

Imagine the following scenarios:

  • There’s a product filter that makes use of product attributes. The shop manager wants to be able to choose if a particular product attribute is displayed in the filter or not.
  • There’s a pre-defined list of product types that are sold in a store. The shop manager wants to be able to associate product attributes to one of the product types. Products of a certain type have their associated product attributes automatically added to them.

These are cases where we could benefit from being able to associate product attributes to custom data. Unfortunately, this isn’t as simple as it could seem at first glance. We cannot use the WordPress metadata API as we would with posts and terms.

In this tutorial, I’ll explain my approach to associate custom data with WooCommerce product attributes. You can also find the final result on Github.

This tutorial assumes that you have prior knowledge of:

What are WooCommerce product attributes?

WooCommerce product attributes are a way to group products by their characteristics. A product attribute (e.g: color) is formed by terms (e.g: black, white, purple). WooCommerce product attributes can be used in several ways:

  • To group products that share the same product attribute (e.g: display a list of t-shirts that are available in purple), as it occurs in WooCommerce’s filter widget.
  • To create variable products (e.g: allow the user to select a color from the list of colors the t-shirt is available in).
  • To display in the product’s “additional info” tab (e.g: display a list of all the colors a t-shirt is available in).

How does WooCommerce handle product attributes internally?

Internally, each of the WooCommerce product attributes is its own taxonomy. Each of these taxonomies is defined by the shop manager in the Products > Attributes admin page.

Taxonomies, like custom post types, aren’t stored anywhere in the database by WordPress. They’re defined somewhere in the code and registered at runtime. Only terms (each of the items in a taxonomy) are stored persistently and can have metadata associated with them through the WordPress metadata API.

If WordPress doesn’t store taxonomies in the database, how does WooCommerce know which product attributes has the shop manager created?

WooCommerce stores product attributes in a custom table (wp_woocommerce_attribute_taxonomies), and does its own custom implementation of getting, adding, modifying, and deleting product attributes.

And although WooCommerce provides its share of handy functions, it does not provide an equivalent of the metadata API for product attributes, nor a table to store such data. In fact, the additional fields that WooCommerce provides for product attributes, such as “Enable archive?” or “Default sort order”, are columns of the wp_woocommerce_attribute_taxonomies table.

How to add custom fields (metadata) to WooCommerce product attributes

Since neither WooCommerce nor WordPress provide a way to add metadata to product attributes, we will need to do our own implementation.

Database storage

For the purpose of this tutorial I’ve decided to take the simplest route, that is using the WordPress options API to store all our product attribute metadata in a serialized array inside the wp_options table.

We will tell WordPress that we have an option called ssanzdev_wc_product_att_meta that contains an array with the following structure:

array(
	$product_attribute_id_1 => array(
		$meta_key_1 = 'w',
		$meta_key_2 = 'x',
	),
	$product_attribute_id_2 => array(
		$meta_key_1 = 'y',
		$meta_key_2 = 'x',
	)
);

Whenever we need to access any of the product attribute metadata, we will use the function get_option('ssanzdev_wc_product_att_meta') to get the array, and look if the product attribute id and meta key pair exist in the array.

Because WordPress saves options to its object cache when they are retrieved for the first time, there will be no additional database queries in the same page load even if we need to call get_option('ssanzdev_wc_product_att_meta') several times.

Drawbacks

You’re probably safe using this approach. It is often used by themes and plugins to save their configuration options, but there are a couple things that you should keep in mind.

It doesn’t scale well

We store all the data in the same field in the database, and we need to load it all onto memory whenever we need to look up something.

Field length is unlikely to be a problem. The option_value column of the wp_options table is of type LONGTEXT, which can hold around 1,000,000 pages of text.

But you don’t want to be wasting your precious server memory loading lots of data that you aren’t going to use.

You may prefer to look at alternatives if you anticipate that you will have lots of product attributes, custom fields, or custom fields that will be particularly large (such as text areas); or if it’s part of a plugin that you plan to release that may be used in unexpected ways.

It doesn’t lend itself to do database queries based on metadata

In order to not pollute the wp_options table, I’ve decided to store all the product attribute metadata under the same option in a serialized array.

It makes our table cleaner, but it also makes it very difficult to look for and return certain values inside the array without deserializing it first.

For example, if we wanted to get a list of product attribute ids that had a certain value in one of their meta keys, we would need to load and deserialize the array first, and iterate through it to check every value and discard those that don’t match. If we were using the metadata API, we would be able to do a meta query to extract that information directly from the database.

Alternatives

Here are some storage alternatives that I won’t be covering in this tutorial.

  • Create a separate option per product attribute and meta key (something along the lines of wc_product_att_fields_{$meta_key}_{$product_att_id}). This would quickly pollute the wp_options table though so I don’t recommend it.
  • Create a custom table to handle product attribute meta data, using the dbDelta function. This would require us to write all the add, update, delete and retrieve logic ourselves.
  • Create a custom taxonomy that mirrors WooCommerce product attributes, automatically creating one term per attribute, and using the term meta functions and table. This would require hooking to product attributes creation, modification and deletion to keep our terms updated. This is probably the approach I would use if I was building a commercial plugin.

Adding custom fields to the product attribute forms

For the purpose of this tutorial, I will assume the case that we want to add a checkbox field to every product attribute so the shop manager can select whether an attribute should appear in a product filter in the frontend or not.

I’ve prefixed my functions and custom fields with ssanzdev_ to avoid collisions. Of course, rename those to whatever you want; or even better, use namespaces as in the GitHub example.

In both the add and edit product attribute forms, WooCommerce provides hooks that we can latch onto to add our custom field.

To the “add attribute” form

Here I’m adding a checkbox at the end of the add form, respecting WordPress’ CSS classes and markup for the form.

function ssanzdev_field_add_page()
{ ?>

    <div class="form-field">
        <label for="ssanzdev_use_in_filter">
            <input type="checkbox" id="ssanzdev_use_in_filter" name="ssanzdev_use_in_filter" value="1">
            <?php esc_html_e('Use attribute in filter', 'ssanzdev-wc-product-att-field'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Check if you want to display this product attribute in the store\'s filter.', 'ssanzdev-wc-product-att-field'); ?>
        </p>
    </div> <?php

}
add_action('woocommerce_after_add_attribute_fields', 'ssanzdev_field_add_page');

To the “edit attribute” form

On the edit page there are two main differences from the add page:

  • The form markup changes a little bit.
  • We need to get the current value of the meta field for the product attribute being edited, to fill the field with the current value by default. Since we still haven’t seen how to retrieve it, we will set it to false for now.
function ssanzdev_field_edit_page()
{
    
    // Get the id of the product attribute being edited.
    // It's not passed as a parameter, so we have to get it from the URL.
    $product_att_id = isset($_GET['edit']) ? absint($_GET['edit']) : 0;

    // Get the current value of the "use in filter" field for the product
    // attribute being edited.
    $use_in_filter = false; ?>

    <tr class="form-field">
        <th scope="row" valign="top">
            <label for="ssanzdev_use_in_filter">
                <?php esc_html_e('Use attribute in filter', 'ssanzdev-wc-product-att-field'); ?>
            </label>
        </th>
        <td>
            <div>
                <input type="checkbox" id="ssanzdev_use_in_filter" name="ssanzdev_use_in_filter" value="1" <?php checked($use_in_filter, true); ?>>
            </div>
            <p class="description">
                <?php esc_html_e('Check if you want to display this product attribute in the store\'s filter.', 'ssanzdev-wc-product-att-field'); ?>
            </p>
        </td>
    </tr> <?php

}
add_action('woocommerce_after_edit_attribute_fields', 'ssanzdev_field_edit_page');

CRUD functions

Now that we have our checkbox showing in the admin panel, let’s proceed with how to retrieve, save, update and delete our data.

Get all the product attribute meta

First, we’ll write a function that retrieves our array of product attribute metadata from the database.

Let’s make sure that it always returns an array for consistency, even if the field doesn’t exist or contains unexpected data.

function ssanzdev_get_all_product_att_meta()
{
    
    $all_fields = get_option('ssanzdev_wc_product_att_fields');
    
    if (!is_array($all_fields) ) {
        $all_fields = [];
    }

    return $all_fields;

}

Get meta by product attribute id and meta key

Let’s make the equivalent of get_term_meta(), in which by specifying the product attribute id and a meta key, we get the value of that specific field. If we leave the $meta_key parameter empty, an array with all the metadata associated with the product attribute is returned.

To do this, we check if the specified $product_att_id and $meta_key exist as indexes of our metadata array.

function ssanzdev_get_product_att_meta( $product_att_id, $meta_key = '' )
{    
    
    $all_fields = ssanzdev_get_all_product_att_meta();

    // If we pass an empty key, it will return data for all keys.
    if (empty($meta_key) ) {
        $field_exists = isset($all_fields[$product_att_id]);
        $field_value = $field_exists ? $all_fields[$product_att_id] : [];
    // If we specify a key, it will only return data of the specified key.
    } else {
        $field_exists = isset($all_fields[$product_att_id][$meta_key]);
        $field_value = $field_exists ? $all_fields[$product_att_id][$meta_key] : false;
    }

    return $field_value;

}

Now we can go back to our field_edit_page() function and get the current value of the field for the product attribute being edited.

Replace this line:

$use_in_filter = false; ?>

With this:

$use_in_filter = ssanzdev_get_product_att_meta( $product_att_id, 'use_in_filter' ); ?>

But let’s do a little improvement on it before continuing. We’ll create a little sanitization function to make sure use_in_filter always returns a boolean value.

function ssanzdev_sanitize_boolean( $value )
{
    return filter_var($value, FILTER_VALIDATE_BOOLEAN);
}

And back to the field_edit_page() function, let’s filter the returned value through our sanitization function.

$use_in_filter = ssanzdev_sanitize_boolean(ssanzdev_get_product_att_meta($product_att_id, 'use_in_filter')); ?>

Updating product attribute meta

To update a field, we’ll need to load the entire metadata array, and insert the new value in the specified $product_att_id and $meta_key index combination.

If the index doesn’t exist, it’s created anew. If it did exist, it will be overwritten, so the function can be used to create new fields as well as to modify existing ones.

Finally, we save our modified array to the database using the update_option() function from the options API.

function ssanzdev_update_product_att_meta( $product_att_id, $meta_key, $value )
{
    $all_fields = ssanzdev_get_all_product_att_meta();

    // Add product attribute id to array if it doesn't exist.
    if (!isset($all_fields[$product_att_id]) ) {
        $all_fields[$product_att_id] = [];
    }

    $all_fields[$product_att_id][$meta_key] = $value;

    update_option('ssanzdev_wc_product_att_fields', $all_fields);

}

Deleting product attribute meta

Similarly to what we did in the update_product_att_meta() function, to delete metadata from a product attribute, we’ll have to load the array whole, find the specified $product_att_id and $meta_key index combination, and unset it if it exists. And again, we’ll pass the modified array to update_option() to make the change permanent.

If we leave the $meta_key parameter empty, it will wipe all the data associated with the product attribute, which we will use to clean up after an attribute is deleted.

function ssanzdev_delete_product_att_meta( $product_att_id, $meta_key = '' )
{

    $all_fields = ssanzdev_get_all_product_att_meta();

    // If $meta_key not provided, delete all metadata of product attribute.
    if (empty($meta_key) ) {
        
        if (isset($all_fields[$product_att_id]) ) {
            unset($all_fields[$product_att_id]);
        }

    // If $meta_key is provided, delete only value with the key.
    } else {

        if (isset($all_fields[$product_att_id][$meta_key]) ) {
            unset($all_fields[$product_att_id][$meta_key]);
        }

    }

    update_option('ssanzdev_wc_product_att_fields', $all_fields);

}

Hooking onto product attribute save, update and delete events

The only thing left to do is to update our metadata array when a product attribute is saved, updated, or deleted.

On create new product attribute

First thing, we do a couple security checks that are recommended whenever a user submits data (in this case, we’re in hooking the middle of the process of submitting the form that adds a new product attribute):

We will perform the same verifications when updating and deleting product attributes.

Next, we will be checking if our custom field has been sent in the form, and sanitize the sent value before saving it to the database, using the sanitize_boolean() function we created, to make sure the value is a boolean.

If the value it’s set to true, we will save it to our array using the update_product_att_meta() function, while if it’s set to false we will delete it from our array using the delete_product_att_meta(). We could also save it as false, but since it’s a boolean value and it being missing will default to false anyway, I figured that I’d rather have a smaller array than one with values set to false.

function ssanzdev_on_save_product_att( $id, $data )
{

    // Security check: Verify nonce to protect against CSRF.
    check_admin_referer('woocommerce-add-new_attribute');

    // Security check: Verify user has permission to perform this action.
    if (!current_user_can('manage_product_terms') ) {
        return;
    }

    $use_in_filter = isset($_POST['ssanzdev_use_in_filter']) ? ssanzdev_sanitize_boolean($_POST['ssanzdev_use_in_filter']) : false;

    if ($use_in_filter ) {
        ssanzdev_update_product_att_meta($id, 'use_in_filter', $use_in_filter);
    } else {
        ssanzdev_delete_product_att_meta($id, 'use_in_filter');
    }

}
add_action('woocommerce_attribute_added', 'ssanzdev_on_save_product_att', 10, 2);

On edit product attribute

When updating an existing product attribute, we’ll do the same we did on add: security checks, sanitize value, and update the array.

function ssanzdev_on_update_product_att( $id, $data, $old_slug )
{

    // Security check: Verify nonce to protect against CSRF.
    check_admin_referer('woocommerce-save-attribute_' . $id);

    // Security check: Verify user has permission to perform this action.
    if (!current_user_can('edit_product_terms') ) {
        return;
    }

    $use_in_filter = isset($_POST['ssanzdev_use_in_filter']) ? ssanzdev_sanitize_boolean($_POST['ssanzdev_use_in_filter']) : false;

    if ($use_in_filter ) {
        ssanzdev_update_product_att_meta($id, 'use_in_filter', $use_in_filter);
    } else {
        ssanzdev_delete_product_att_meta($id, 'use_in_filter');
    }

}
add_action('woocommerce_attribute_updated', 'ssanzdev_on_update_product_att', 10, 3);

On delete product attribute

When deleting a product attribute, we need to make sure to delete all the metadata associated with it.

To achieve this, after doing our security checks, we’ll call the delete_product_att_meta() function without a second parameter. By providing only the product attribute id and not a specific meta key, we’ll be deleting all the data associated with the product attribute.

function ssanzdev_on_delete_product_att( $id, $data, $taxonomy )
{

    // Security check: Verify nonce to protect against CSRF.
    check_admin_referer('woocommerce-delete-attribute_' . $id);

    // Security check: Verify user has permission to perform this action.
    if (!current_user_can('delete_product_terms') ) {
        return;
    }

    // If we don't provide a second parameter to the function, it deletes
    // all the meta data associated to the product attribute id.
    ssanzdev_delete_product_att_meta($id);

}
add_action('woocommerce_attribute_deleted', 'ssanzdev_on_delete_product_att', 10, 3);

Example of usage

To finish up, let’s see an example of how we could use this metadata.

We’ll write a function that returns only the product attributes that the shop manager has flagged as “use in filter”. To do this, we’ll get all the product attributes with the wc_get_attribute_taxonomies() function and filter out those who don’t have the field use_in_filter set to true.

function ssanzdev_get_product_atts_filter()
{

    $product_atts = wc_get_attribute_taxonomies();

    foreach ( $product_atts as $index => $product_att ) {
        if (!ssanzdev_get_product_att_meta($product_att->attribute_id, 'use_in_filter') ) {
            unset($product_atts[$index]);
        }
    }

    return $product_atts;

}

Now, we’ll display a list of the product attributes flagged as “use in filter” and their terms.

function ssanzdev_display_product_atts_filter()
{

    $product_atts = ssanzdev_get_product_atts_filter();

    if (!empty($product_atts) ) : ?>
        <ul>
            <?php foreach ( $product_atts as $product_att ): ?>
                <li>
                    <?php echo esc_html($product_att->attribute_label); ?>
                    <?php $product_att_terms =  get_terms(array( 'taxonomy' => wc_attribute_taxonomy_name($product_att->attribute_name), 'hide_empty' => false )); ?>
                    <?php if (!empty($product_att_terms) ) : ?>
                        <ul>
                            <?php foreach ( $product_att_terms as $product_att_term ): ?>
                                <li>
                                    <?php echo esc_html($product_att_term->name); ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif;

}

Remember that you can find the whole result of this tutorial on GitHub, with some additional commentary.

Leave a Reply

Your email address will not be published. Required fields are marked *