How to update WooCommerce wp_wc_product_attributes_lookup table programatically?

If you are using WooCommerce, you may be familiar with the wp_wc_product_attributes_lookup table. This table is used to improve the performance of WooCommerce and is typically updated automatically.

However, if you make changes to the attributes of a product directly in the wp_postmeta table, the wp_wc_product_attributes_lookup table may not be updated immediately. For example, you may have a snippet of code similar to this:

    $product_id = 46;
    $product_attr = get_post_meta($product_id, '_product_attributes',true);

    $product_attr["pa_color"] = [
        'name' => "pa_color",
        'value' => '',
        'is_visible' => '0',
        'is_taxonomy' => '1'
    ];

    wp_set_object_terms($product_id, "Blue", 'pa_color' , true );
    update_post_meta($product_id, '_product_attributes', $product_attr);

To manually trigger this update, you can use the LookupDataStore class. First, you will need to add the following line of code at the top of your plugin or theme PHP file:

use Automattic\WooCommerce\Internal\ProductAttributesLookup\LookupDataStore;

Then, you can use the create_data_for_product function of the LookupDataStore class to create the product attributes in the lookup table for a specific product_id.

For example:

$lookupDataStore = new LookupDataStore();
$lookupDataStore->create_data_for_product($product_id);

This can be helpful if you are making direct changes to the product attributes in the wp_postmeta table and want to ensure that the wp_wc_product_attributes_lookup table is also updated.

Leave a Comment