I have a post type of listing. In each listing is post object named package that is connected to another post type of package. There is then a field attached to each package named sort. I need to be able to use the sort value to order the listings.
add_action('pre_get_posts','alter_query');
function alter_query($query) {
global $wp_query;
if( $query->is_main_query() && is_post_type_archive( 'listing' ) ) {
// Package is a post object attached to the listing post type.
// It allows you to select from a packages post type.
$package = get_field('package');
// Sort is a numeric field attached to the packages post type.
$sort = get_field('sort',$package->post_ID);
$query->set('orderby', array(
...
));
remove_all_actions ( '__after_loop');
}
}
You cannot sort posts by a meta value attached to a different post. You can only sort posts by meta fields attached to the post you are sorting. There simply is not a way to do this in WP.
posts you are sorting
=> meta values of these posts <= you can sort by these
=> Related post
=> meta values of related posts <= you cannot sort the first level posts by this