Skip to content

Instantly share code, notes, and snippets.

@birgire
Last active October 4, 2024 16:53
Show Gist options
  • Save birgire/0ed300ae4436fcaf508c to your computer and use it in GitHub Desktop.
Save birgire/0ed300ae4436fcaf508c to your computer and use it in GitHub Desktop.
WordPress: WooCommerce Product Attributes - Bulk Modifier ( from custom meta attributes to taxonomy attributes)
<?php
/**
* Plugin Name: WooPAM: Woo Product Attributes Modifier
* Description: Bulk update 'custom meta product attributes' to 'taxonomy product attributes' in WooCommerce. Supports the GET variables, like: woopam_mode=run&woopam_from_attribute_meta=colour&woopam_to_attribute_tax=pa_colour&woopam_keep_attribute_meta&woopam_posts_per_page=10&woopam_paged=0&woopam_post_type=product&woopam_post_status=any. WARNING: Backup DB first!!!
* Plugin Author: birgire
* Author URI: https://github.com/birgire
* Plugin URI: https://gist.github.com/birgire/0ed300ae4436fcaf508c
* Version: 1.0.0
* License: GPL2+
* Text Domain: woopam
* Requires PHP: 5.4
*/
/*
*---------
* Support:
*---------
* If this helped your project and saved you some time, you can support the developement here:
*
* https://www.buymeacoffee.com/birgire
*
* Thanks.
*
*---------------
* Usage Example:
*---------------
*
* To change all custom product meta attributes "color" to "pa_color" products taxonomy (where pa_ is a WooCommerce auto-added prefix), we can run:
*
* https://example.com/?woopam_mode=run&woopam_from_attribute_meta=color&woopam_to_attribute_tax=pa_color&woopam_keep_attribute_meta=1&woopam_posts_per_page=100&woopam_paged=0&woopam_post_type=product&woopam_post_status=any
*
* REMEMBER: Create the product taxonomy beforehand here (without pa_ prefixing it yourself):
*
* https://example.com/wp-admin/edit.php?post_type=product&page=product_attributes
*
* WARNING: Remember to backup your database first!!!
*
*-----------
* CHANGELOG:
*-----------
*
* 2021-12-13 v1.0.0 Overhaul (Work: 5 hours)
*
*------
* TODO:
*------
*
* - Split into more smaller functions.
* - Add tests.
* - Add more documentation.
* - Look into UI.
*/
add_action( 'template_redirect', function() {
// Activate product attribute modification (only available for admins).
if ( ! current_user_can( 'manage_options' ) || 'run' !== filter_input( INPUT_GET, 'woopam_mode' ) ) {
return;
}
// User input.
$keep_attribute_meta = filter_input( INPUT_GET, 'woopam_keep_attribute_meta', FILTER_VALIDATE_BOOLEAN );
$from_attribute_meta = filter_input( INPUT_GET, 'woopam_from_attribute_meta', FILTER_SANITIZE_STRING );
$to_attribute_tax = filter_input( INPUT_GET, 'woopam_to_attribute_tax', FILTER_SANITIZE_STRING );
$post_type = filter_input( INPUT_GET, 'woopam_post_type', FILTER_SANITIZE_STRING );
$post_status = filter_input( INPUT_GET, 'woopam_post_status', FILTER_SANITIZE_STRING );
$posts_per_page = filter_input( INPUT_GET, 'woopam_posts_per_page', FILTER_SANITIZE_NUMBER_INT );
$paged = filter_input( INPUT_GET, 'woopam_paged', FILTER_SANITIZE_NUMBER_INT );
// Default values.
if ( empty( $posts_per_page ) ) {
$posts_per_page = 10;
}
if ( empty( $paged ) ) {
$paged = 1;
}
if ( empty( $post_type ) ) {
$post_type = 'product';
}
if ( empty( $keep_attribute_meta ) ) {
$keep_attribute_meta = false;
}
if ( empty( $post_status ) ) {
$post_status = 'any';
}
if ( empty( $from_attribute_meta ) || empty( $to_attribute_tax ) ) {
wp_die( esc_html__( 'Oh, rembember that the "from_attribute_meta" and "to_attribute_tax" variable must be set!', 'woopam' ) );
}
$meta_key = '_product_attributes';
// Fetch products with product attributes:
$args = array(
'post_type' => sanitize_key( $post_type ),
'fields' => 'ids',
'posts_per_page' => (int) $posts_per_page,
'paged' => absint ( $paged ),
'meta_key' => $meta_key,
'post_status' => sanitize_key( $post_status ),
);
$post_ids = get_posts( $args );
$total = 0;
$total_modified = 0;
$msg = esc_html__( "Bulk update 'custom meta product attributes' to 'taxonomy product attributes'", 'woopam' );
printf(
'<h1>%s</h1>%s<ul>',
$msg,
esc_html__( 'START', 'woopam' )
);
foreach ( (array) $post_ids as $post_id ) {
$total++;
$meta = get_post_meta( $post_id, $meta_key, true );
$product_needs_update = false;
foreach ( (array) $meta as $key => $terms ) {
// Locate our meta attribute.
if ( $from_attribute_meta === $terms['name'] ) {
$product_needs_update = true;
$tmp = explode( '|', $terms['value'] );
$product_terms = array();
foreach ( (array) $tmp as $term ) {
$product_terms[] = $term;
}
// Remove the product meta attribute:
if ( ! $keep_attribute_meta ) {
unset( $meta[$key] );
}
// Add it again as product taxonomy attribute:
$meta["{$to_attribute_tax}"] = array(
'name' => "{$to_attribute_tax}",
'value' => '',
'position' => $terms['position'],
'is_visible' => $terms['is_visible'],
'is_variation' => $terms['is_variation'],
'is_taxonomy' => 1,
);
} // end if
} // end foreach
echo '<li>';
if ( $product_needs_update ) {
// Assign terms to the post (create them if they don't exists).
$term_taxonomy_ids = wp_set_object_terms( $post_id, $product_terms, $to_attribute_tax, false );
if ( is_wp_error( $term_taxonomy_ids ) ) {
$msg = sprintf(
esc_html__( 'Error! Terms couldn\'t be set for product id: %d and WP error description: "%s" and product taxonomy slug: "%s"', 'woopam' ),
(int) $post_id,
esc_html( $term_taxonomy_ids->get_error_code() ),
esc_html( $to_attribute_tax )
);
printf( '<strong>%s</strong><br/>', $msg );
} else {
update_post_meta( $post_id, $meta_key, $meta );
$total_modified++;
$msg = sprintf(
esc_html__( 'Success! The taxonomy post attributes were set for product id: %d', 'woopam' ),
(int) $post_id
);
printf( '<strong>%s</strong><br/>', $msg );
}
} else {
$msg = sprintf(
esc_html__( 'Nothing to do here! No product attributes were set for product id: %d', 'woopam' ),
$post_id
);
printf( '%s<br/>', $msg );
}
echo '</li>';
} // end foreach post.
echo '</ul><br/>';
printf(
esc_html__( 'Total products checked: %d', 'woopam' ),
(int) $total
);
echo '<br/>';
printf(
esc_html__( 'Total modified products: %d', 'woopam' ),
(int) $total_modified
);
echo '<br/>';
echo '<br/>';
die( esc_html__( 'END', 'woopam' ) );
} );
@hornmedia
Copy link

How can i start this plugin ?? :)

@digitalka
Copy link

Dude I love you. You saved me HUGE amount of work

@lommaker
Copy link

lommaker commented Mar 7, 2019

How can i start this plugin??

@valiermedia
Copy link

For those of you who are asking how to start this plugin:

  1. Place the PHP file in a folder named woo-product-attributes-bulk-modifier. It needs to be in the directory root, not in a subfolder.
  2. Either FTP that folder to your plugins directory, or zip the file and go to "Add Plugin" and then upload the zip file via WP
  3. Activate the plugin
  4. Ensure that the product attribute has already been created, this plugin will migrate custom attributes to an EXISTING product attribute. If it hasn't been created, create it.
  5. Visit the following URL (swapping out the variables as needed - variables are in all caps): http://WWW.YOURSITE.COM/?wpq_mode=run&wpq_from=COLOUR&wpq_to=pa_COLOUR&wpq_ppp=100&wpq_offset=0&wpq_post_type=product&wpq_post_status=any

The plugin should list all of the IDs of the products that have been updated. If it only says "Done!" that means that the plugin did not find a matching term for the "to" variable.

@jonfitzgerald
Copy link

Thanks so much for this!

I’m having some trouble though, keep receiving the “Done!” message without any products being updated. Both variables are set correctly.

Is there anything else I should check?

@Majed-RO
Copy link

A small modification:

instead of ( line 91 ):
// Remove the product meta attribute:
unset( $meta[$from] );

replace it with:
// Remove the product meta attribute:
unset( $meta[$key] );

Because in some cases if you write the custom attribute in a capital letter, it will not unset it.

@wickywills
Copy link

Doesn't seem to work correctly. For example, I have an attribute named "L/XL", but running this script creates a new attribute called "lxl" and doesn't use the one I created.

@thomastruett
Copy link

Are you aware if it is possible to execute the script above and also maintain the variation relationships that were created using the custom attributes? For example, I am migrating from a custom attribute (size) to a taxonomy attribute (pa_size). Before the migration, one of my products has 5 variations based on the custom attribute size (e.g. 10, 12, 14, 16, 18). After I run the migration, it appears that all of the product variations have been orphaned (screenshot attached) and have to be manually re-created.
Screen Shot 2019-11-17 at 18 40 38

@chillpilllike
Copy link

the code is not working with latest woocommerce

@chillpilllike
Copy link

gives the error There was an error somewhere and the terms couldn't be set for post_id

@jlapitan
Copy link

Error message says - ** Invalid taxonomy.**

@ecub
Copy link

ecub commented Dec 12, 2021

Plugin doesn't transfer attributes written in languages ​other than English, is it possible to fix it somehow?

@birgire
Copy link
Author

birgire commented Dec 13, 2021

Hi all, thanks for your comments, I forgot about the script for a long time :-)

I will look into the reported problems above.

@birgire
Copy link
Author

birgire commented Dec 13, 2021

I've updated to version 1.0.0 and hopefully fixing the issues mentioned here above.

Notice the new GET parameters names

@birgire
Copy link
Author

birgire commented Dec 13, 2021

Here are some screenshots from the runs:

  1. Nothing do to:

image

  1. Missing product taxonomy:

image

  1. Success:

image

@klemensh
Copy link

Hello @birgire thanks a lot for this snipped. I'm also trying to convert a custom product attribute in a global attribute (for translation). Unfortunately I get the error message "invalid_taxonomy" even though my global taxonomy does exist. I'm using the latest WooCommerce version.

@birgire
Copy link
Author

birgire commented Dec 21, 2021

Hello @klemensh

I wonder what query string you use and what's the name/slug of the attribute taxonomy?

@waltone57
Copy link

This plugin almost seem like answer to my problem but I have same problem than thomastruett earlier. For some reason it just adds global variables to product but does not remove custom one or replace attributes in the stock page. It shows custom attribute with value and global attribute with "any size".

Am I doing something wrong?

@smoovo
Copy link

smoovo commented Nov 9, 2022

Hi, just to help anyone that comes to this page sharing the same problem. Custom attribute to global (taxonomy), variations, etc...

How we solved it easily:

  1. We created the same name of the Custom Attribute as a Global Attribute (Brand => Brand). No need to add terms, just attribute Name.
  2. Downloaded (Export) all the products as CSV file on the All Products table page.
  3. On the CSV file (opened on Excel) make sure to set Attribute n global (n is the number of attribute, 1, 2, etc...) to 1 (when it's custom it will show 0). Do this on all rows that have the attribute you are converting.
  4. To make sure Variations also saved and that attribute can be used make sure that Attribute n visible is also set to 1 on all rows.
  5. Save the file.
  6. Next go back to your All Products page and click on Import.
  7. Choose the file and check the box that says "Existing products that match by ID or SKU will be updated. Products that do not exist will be skipped.".
  8. Next click on Run the importer button.

This will convert all the custom attributes with their terms into global, and also keep all the variations. No need for any coding or hard work.

For the steps 3 and 4 you can use formula like this one =IF(AN2="Flavors","1","") for the first line and copy paste it to all rows to do it automatically for a specific attribute if needed.

Hopefully this will help you.

@realweb11
Copy link

realweb11 commented Feb 19, 2023

To also preserv the variations, I added this code after the row "update_post_meta( $post_id, $meta_key, $meta );":

$args = array(
    'post_type' => 'product_variation',
    'post_status' => 'any',
    'post_parent' => $post_id,
    'fields' => 'ids',
    'posts_per_page' => -1
);
$variations = get_children( $args );
if ( is_array( $variations ) && count( $variations ) > 0 ) {
    foreach ( $variations as $variation_id ) {
        $term = get_post_meta( $variation_id, 'attribute_' . strtolower( $from_attribute_meta ), true );
        delete_post_meta( $variation_id, 'attribute_' . strtolower( $from_attribute_meta ) );
        update_post_meta( $variation_id, 'attribute_' . $to_attribute_tax, strtolower( $term ) );
    }
    $default_attributes = get_post_meta( $post_id, '_default_attributes', true );
    if ( is_array( $default_attributes ) ) {
        foreach ( $default_attributes as $key => $term) {
            if ( $key == strtolower( $from_attribute_meta ) ) {
                unset( $default_attributes[$key] );
                $default_attributes[$to_attribute_tax] = strtolower( $term );
            }
        }
        update_post_meta( $post_id, '_default_attributes',  $default_attributes );
    }
}

@birgire
Copy link
Author

birgire commented Feb 24, 2023

Thanks for your feedback @smoovo and @realweb11

@emmelemme
Copy link

Hey @birgire thank you so much for this code!

I've made some adjustments that refine variations handling, since the attribute name get slugified and my terms had some special chars in them I had problems with both the import method and the @realweb11 code above.

Line 105

/* Get only products that shares the target attribute */
'meta_query' => [
    [
        'key' => $meta_key,
        'compare' => 'LIKE',
        'value' => sprintf('"%s"', $from_attribute_meta)
    ]
],

Line 129

/* Selected target attribute by slug to avoid issues with spaces and special characters */
if ( $from_attribute_meta === $key ) {

Line 172

/* Added code from @realweb11 with the correction of the slug for the new term (used sanitize_title instead of strtolower) */
$args = array(
    'post_type' => 'product_variation',
    'post_status' => 'any',
    'post_parent' => $post_id,
    'fields' => 'ids',
    'posts_per_page' => -1
);

$variations = get_children( $args );

if ( is_array( $variations ) && count( $variations ) > 0 ) {
    foreach ( $variations as $variation_id ) {
        $term = get_post_meta( $variation_id, 'attribute_' . strtolower( $from_attribute_meta ), true );
        delete_post_meta( $variation_id, 'attribute_' . strtolower( $from_attribute_meta ) );
        update_post_meta( $variation_id, 'attribute_' . $to_attribute_tax, sanitize_title( $term ) );
    }

    $default_attributes = get_post_meta( $post_id, '_default_attributes', true );

    if ( is_array( $default_attributes ) ) {
        foreach ( $default_attributes as $key => $term) {
            if ( $key == strtolower( $from_attribute_meta ) ) {
                unset( $default_attributes[$key] );
                $default_attributes[$to_attribute_tax] = sanitize_title( $term );
            }
        }
        update_post_meta( $post_id, '_default_attributes',  $default_attributes );
    }
}

Note: With these modifications, it's crucial that the parameter woopam_from_attribute_meta is the slug of the starting attribute.
Thank you again for your gist!

@birgire
Copy link
Author

birgire commented Jan 5, 2024

Awesome, thank you for sharing @emmelemme

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment