Last active
August 3, 2023 13:47
-
-
Save felipeelia/1214cede99a9bf27df68db3086dabf56 to your computer and use it in GitHub Desktop.
Bring featured products first in a WP_Query
This file contains hidden or 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
<?php | |
// Add this to your `functions.php` or (preferably) to a plugin: | |
function featured_products_orderby( $orderby, $query ) { | |
global $wpdb; | |
if ( 'featured_products' == $query->get( 'orderby' ) ) { | |
$featured_product_ids = (array) wc_get_featured_product_ids(); | |
if ( count( $featured_product_ids ) ) { | |
$string_of_ids = '(' . implode( ',', $featured_product_ids ) . ')'; | |
$orderby = "( {$wpdb->posts}.ID IN {$string_of_ids} ) " . $query->get( 'order' ); | |
} | |
} | |
return $orderby; | |
} | |
add_filter( 'posts_orderby', 'featured_products_orderby', 10, 2 ); | |
// Pass `featured_products` as `orderby` parameter: | |
$products = new WP_Query( array( | |
'post_type' => 'product', | |
'orderby' => 'featured_products', | |
) ); |
function featured_products_orderby( $orderby, $query ) {
global $wpdb;if ( 'featured_products' == $query->get( 'orderby' ) ) {
$featured_product_ids = (array) wc_get_featured_product_ids();
if ( count( $featured_product_ids ) ) {
$string_of_ids = '(' . implode( ',', $featured_product_ids ) . ')';
$orderby = "( {$wpdb->posts}.ID IN {$string_of_ids}) " . $query->get( 'order' )." , post_date DESC";
}
}return $orderby;
}
add_filter( 'posts_orderby', 'featured_products_orderby', 10, 2 );
Thank you!
I add sort products by date.
Thank you, guys, it works excellent!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great! Thank you very much.