Created
March 8, 2022 15:05
-
-
Save Alimir/13031e39791f7153cb83e85b0d328387 to your computer and use it in GitHub Desktop.
sort posts by likes in archive pages
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
<?php | |
function wp_ulike_pro_custom_pre_archive($query) { | |
/* only proceed on the front end */ | |
if( is_admin() ) { | |
return; | |
} | |
if ( ( is_category() || is_tag() || is_archive() ) && $query->is_main_query() ) { | |
// Get current meta Query | |
$meta_query = $query->get( 'meta_query' ); | |
// If there is no meta query when this filter runs, it should be initialized as an empty array. | |
if ( ! $meta_query ) { | |
$meta_query = []; | |
} | |
// Append our meta query | |
$meta_query[] = array( | |
'relation' => 'OR', | |
array( | |
'key' => 'like_amount', | |
'compare' => '>=', | |
'value' => 1, | |
'type' => 'NUMERIC' | |
), | |
array( | |
'key' => 'like_amount', | |
'compare' => 'NOT EXISTS' | |
) | |
) ; | |
$query->set( 'meta_query', $meta_query ); | |
$query->set( 'orderby', array( 'meta_value_num' => 'DESC', 'date' => 'DESC' ) ); | |
} | |
} | |
add_filter( 'pre_get_posts', 'wp_ulike_pro_custom_pre_archive' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment