Home > Mobile >  How to update wp_wc_product_attributes_lookup table after running update_post_meta?
How to update wp_wc_product_attributes_lookup table after running update_post_meta?

Time:01-06

I am using the following code to add attributes to a product:

$product_attr = get_post_meta(2, '_product_attributes',true);
      
      $product_attr["pa_product-type"] = [
        'name' => "pa_product-type",
        'value' => '',
        'is_visible' => '0',
        'is_taxonomy' => '1'
        ];  
        
    wp_set_object_terms(2, "Caps", pa_product-type , true );
    update_post_meta(2, '_product_attributes', $product_attr);

The attribute is getting updated successfully in the product and is showing up in product edit page. However, the attribute value is not getting updated in wp_wc_product_attributes_lookup table. How to trigger update in this table after updating/adding attributes using the above code?

CodePudding user response:

This is a very interesting question!

The wp_wc_product_attributes_lookup table is used to improve WooCommerce performance and it's normally updated automatically. There is a class DataRegenerator that handles the product attributes regeneration process. But if you change the attributes directly in the wp_postmeta like 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);

then the wp_wc_product_attributes_lookup table is not updated immediately.

But you can trigger this update manually by using LookupDataStore class.

First you add

use Automattic\WooCommerce\Internal\ProductAttributesLookup\LookupDataStore;

outside your function, for example on the top of the plugin or theme php file or just above your add_action line.

Then you can call the function to create product attributes in the lookup table for a specific product_id


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

Source

  • Related