Last active
April 28, 2023 08:39
-
-
Save mattiasghodsian/b01fba62de8c04803004ea9ae35ae8bd to your computer and use it in GitHub Desktop.
Group simple/variations and group all variations that had same parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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