Skip to content

Instantly share code, notes, and snippets.

@rwkyyy
Created November 24, 2023 18:48
Show Gist options
  • Save rwkyyy/f84887cb55ca301112fbd58a11aa8135 to your computer and use it in GitHub Desktop.
Save rwkyyy/f84887cb55ca301112fbd58a11aa8135 to your computer and use it in GitHub Desktop.
Convert variation to single product (overwrite parent) - via WP CLI - WooCommerce
if (defined('WP_CLI') && WP_CLI) {
function convert_to_simple_products() {
$args = [
'status' => 'publish',
'limit' => -1,
'type' => 'variable',
];
$products = wc_get_products($args);
foreach ($products as $product) {
if ($product->is_type('variable')) {
$variations = $product->get_children();
foreach ($variations as $variation_id) {
$variation = new WC_Product_Variation($variation_id);
$attributes = $variation->get_attributes();
if (isset($attributes['pa_instrument-type']) && $attributes['pa_instrument-type'] === 'YOUR-VARIATION-HERE') {
wp_set_object_terms($product->get_id(), 'simple', 'product_type');
update_post_meta($product->get_id(), '_price', $variation->get_price());
echo "Converted product ID {$product->get_id()} (Variation ID: $variation_id) to a simple product.\n";
break; // Exit the loop after processing the first matching 'stylo' variation
}
}
}
}
echo "Conversion complete.\n";
}
WP_CLI::add_command('convert-stylo-to-simple', 'convert_to_simple_products');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment