Skip to content

Instantly share code, notes, and snippets.

@birgire
Last active March 4, 2024 10:09
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • 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' ) );
} );
@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