Home › Forums › General Issues › Ordering by custom field of relationship field object › Reply To: Ordering by custom field of relationship field object
The posts_join
worked. Posting code below in case it helps anyone else.
$args = array(
'post_type' => 'artworks',
'posts_per_page' => -1,
'no_found_rows' => true,
'order' => 'ASC',
'orderby' => 'artist_name_artwork_title',
);
add_filter('posts_join', 'test_join', 10, 2 );
function test_join($joins, $wp_query) {
if ( $wp_query->get( 'orderby' ) != 'artist_name_artwork_title' ) {
return $joins;
}
global $wpdb;
$joins .= " LEFT JOIN $wpdb->postmeta name ON name.post_id=$wpdb->posts.ID AND name.meta_key='artists_name'" ;
$joins .= " LEFT JOIN $wpdb->postmeta lastname ON lastname.post_id=name.meta_value AND lastname.meta_key='artist_last_name'";
$joins .= " LEFT JOIN $wpdb->postmeta firstname ON firstname.post_id=name.meta_value AND firstname.meta_key='artist_first_name'";
return $joins;
}
add_filter('posts_orderby', 'orderby_artist_name_artwork_title', 10, 2);
function orderby_artist_name_artwork_title($orderby_statement, $wp_query) {
if ( $wp_query->get( 'orderby' ) != 'artist_name_artwork_title' ) {
return $orderby_statement;
}
global $wpdb;
$orderby_statement = "lastname.meta_value, firstname.meta_value, $wpdb->posts.post_title";
return $orderby_statement;
}
$wp_query = new WP_Query( $args );
remove_filter('posts_join', 'test_join', 10 );
remove_filter('posts_orderby', 'orderby_artist_name_artwork_title', 10 );
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.