Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Show and filter grouped WooCommerce products in the post or product list
<?php
// place this code in your theme's functions.php file
function fws_admin_prods_filter( $query ) {
global $pagenow;
if ( is_admin() && $pagenow == 'edit.php' && !empty($_GET['my_grouped_prods'])) {
$query->query_vars['post_parent'] = $_GET['my_grouped_prods'];
}
}
add_filter( 'parse_query', 'fws_admin_prods_filter' );
function admin_filter_grouped_prods() {
global $wpdb;
if (isset($_GET['post_type']) && $_GET['post_type'] == 'product') {
$sql = "SELECT ID, post_title FROM ".$wpdb->posts." WHERE post_type = 'product' AND post_parent = 0 AND post_status IN ('publish', 'private') ORDER BY post_title";
$grouped_prods = $wpdb->get_results($sql, OBJECT_K);
$select = '
<select name="my_grouped_prods">
<option value="">Grouped Products</option>';
$current = isset($_GET['my_grouped_prods']) ? $_GET['my_grouped_prods'] : '';
foreach ($grouped_prods as $prod) {
$childcount = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM ".$wpdb->posts." WHERE post_parent = %d AND post_status IN ('publish', 'private') AND post_type = 'product'", $prod->ID ) );
if ($childcount > 0) {
$select .= sprintf('
<option value="%s"%s>%s</option>', $prod->ID, $prod->ID == $current ? ' selected="selected"' : '', $prod->post_title);
}
}
$select .= '
</select>';
echo $select;
} else {
return;
}
}
add_action( 'restrict_manage_posts', 'admin_filter_grouped_prods' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.