In WooCommerce backend on the productlist, we have the possibility to make a product featured by clicking on the star.
However, if you have a lot of products and you want to see afterwards which products are featured, we have to search through all products.
So I would like to make this column sortable so that all featured products are shown at the front or back during sorting
With my code I have so far, the column can be sorted, but the result becomes empty during sorting, resulting in 0 results
// 'featured' column sortable on the 'product' page
function sc_sortable_column( $columns ) {
$columns['featured'] = 'featured';
return $columns;
}
add_filter( 'manage_edit-product_sortable_columns', 'sc_sortable_column' );
// Orderby 'featured' (product)
function filter_pre_get_posts( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get('orderby');
// featured, product
if( $orderby == 'featured') {
$query->set( 'meta_key', '_featured' );
$query->set( 'orderby', 'meta_value_num' );
}
}
add_action( 'pre_get_posts', 'filter_pre_get_posts' );
Since WooCommerce 3, featured products are now handled by product_visibility custom taxonomy for the term featured. See: Get WooCommerce featured products in a WP_Query
Normally taxonomies doesn't allow posts to be sorted as described in on this WordPress Development StackExchange thread: Using wp_query is it possible to orderby taxonomy?.
But for example using the filter posts_clauses it's possible to sort products by featured.
So the code to be used will be:
// Make Product "Featured" column sortable on Admin products list
add_filter( 'manage_edit-product_sortable_columns', 'products_featured_sortable_column' );
function products_featured_sortable_column( $columns ) {
$columns['featured'] = 'featured';
return $columns;
}
add_filter('posts_clauses', 'orderby_product_visibility', 10, 2 );
function orderby_product_visibility( $clauses, $wp_query ) {
global $wpdb;
$taxonomy = 'product_visibility';
$term = 'featured';
if ( isset( $wp_query->query['orderby'] ) && $term == $wp_query->query['orderby'] ) {
$clauses['join'] .=<<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;
$clauses['where'] .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)";
$clauses['groupby'] = "object_id";
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
$clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
}
return $clauses;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With