Created
October 23, 2020 19:22
-
-
Save andergmartins/0ec13228baa63e47e3771d1c9cb3683e to your computer and use it in GitHub Desktop.
Sort PHP posts by PublishPress editorial metadata
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 | |
/** | |
* @param WP_Query $query | |
* | |
* @return bool | |
*/ | |
function pp_should_change_post_order($query) | |
{ | |
// Add a conditional here to filter when the queries should be filtered. | |
return true; | |
} | |
add_filter('posts_fields', 'pp_order_posts_by_metadata_select', 10, 2); | |
function pp_order_posts_by_metadata_select($fields, $query) | |
{ | |
if (!pp_should_change_post_order($query)) { | |
return $fields; | |
} | |
$fields .= ', IF(pm.meta_value > 0, pm.meta_value, 999999) AS cal_custom_position'; | |
return $fields; | |
} | |
add_filter('posts_join', 'pp_order_posts_by_metadata_join', 10, 2); | |
function pp_order_posts_by_metadata_join($join, $query) | |
{ | |
if (!pp_should_change_post_order($query)) { | |
return $join; | |
} | |
global $wpdb; | |
$join = "LEFT JOIN {$wpdb->postmeta} as pm ON (ID = pm.post_id AND pm.meta_key = '_pp_editorial_meta_number_position')"; | |
return $join; | |
} | |
add_filter('posts_orderby', 'pp_order_posts_by_metadata', 10, 2); | |
function pp_order_posts_by_metadata($orderby, $query) | |
{ | |
if (!pp_should_change_post_order($query)) { | |
return $orderby; | |
} | |
$originalOrderby = $orderby; | |
$orderby = 'cal_custom_position ASC'; | |
if (!empty($originalOrderby)) { | |
$orderby .= ',' . $originalOrderby; | |
} | |
return $orderby; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment