Skip to content

Instantly share code, notes, and snippets.

@mattiasghodsian
Last active April 28, 2023 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattiasghodsian/b01fba62de8c04803004ea9ae35ae8bd to your computer and use it in GitHub Desktop.
Save mattiasghodsian/b01fba62de8c04803004ea9ae35ae8bd to your computer and use it in GitHub Desktop.
Group simple/variations and group all variations that had same parent
/**
* Title: Group simple/variations
* Author Mattias Ghodsian
* Description: Group simple/variations and group all variations that had same parent
* Donate a cup of coffee: https://www.buymeacoffee.com/mattiasghodsian
**/
function wooGroupProducts(){
$args = array( 'post_type' => 'product', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
$data = [];
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
if ($product->is_type( 'variable' ))
{
$available_variations = $product->get_available_variations();
foreach ($available_variations as $variation)
{
$nkey = str_replace( [',','.','-',' '], '_', strtolower($product->name));
$variation['productName'] = $product->name;
$data['variation'][$nkey][] = $variation;
}
}else{
$data['simple'][] = (array)$product;
}
endwhile;
} else {
return 'No products found';
}
wp_reset_postdata();
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment