Last active
November 24, 2020 06:49
-
-
Save kodie/bced2621d0a9a92eb7565fe3fabd695c to your computer and use it in GitHub Desktop.
Create a custom query 'orderby' type that uses data from other tables in WordPress
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 | |
// Fetch data required for custom orderby types and left join it into the query | |
add_filter('posts_join_paged', 'custom_orderby_joiner', 10, 2); | |
function custom_orderby_joiner($join_paged_statement, $wp_query) { | |
$orderby = $wp_query->query_vars['orderby']; | |
if ($orderby === 'popularity') { | |
$join_paged_statement .= " INNER JOIN (SELECT postid, pageviews FROM wp_popularpostsdata) popularpostsdata ON popularpostsdata.postid = wp_posts.ID"; | |
} | |
if ($orderby === 'rating') { | |
$join_paged_statement .= " INNER JOIN (SELECT pack_id, AVG(rating_value) as avg_rating FROM wp_art_ed_pro_pack_ratings GROUP BY pack_id) ratings ON ratings.pack_id = wp_posts.ID"; | |
} | |
return $join_paged_statement; | |
} | |
// Apply custom orderby types | |
add_filter('posts_orderby', 'custom_orderby', 10, 2); | |
function custom_orderby($orderby_statement, $wp_query) { | |
$order = $wp_query->query_vars['order']; | |
$orderby = $wp_query->query_vars['orderby']; | |
if ($orderby === 'popularity') { | |
$orderby_statement = "pageviews $order"; | |
} | |
if ($orderby === 'rating') { | |
$orderby_statement = "avg_rating $order"; | |
} | |
return $orderby_statement; | |
} | |
// Example usage | |
$the_query = new WP_Query(array( | |
'orderby' => 'popularity', // or 'rating' | |
'order' => 'DESC' | |
)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment