Support

Account

Home Forums Front-end Issues Sorting by relational linked user fields

Helping

Sorting by relational linked user fields

  • Does anyone know how to sort an archive page by a relational value?
    I followed instructions here https://support.advancedcustomfields.com/forums/topic/custom-post-type-order-posts-by-a-groups-field-at-archive-page/ which allowed me to sort by the field, and it worked great. In this case, it is a relational user field though, and appears to be sorting by the underlying ID, not the display name.
    It’s still better than the default, sorting by post date, so now the users’ assigned posts are together. It’s not alphabetical though, and makes it seem like I don’t know the alphabet.

    I’m currently doing this, which is sorting by the underlying User ID assigned (assigned_lead). Can I tell it to use assigned_lead[display_name], or something like that?

    function sort_by_date_my_cpt( $query ) {
    if ( is_post_type_archive( ‘items_to_track’) ) {
    $query->set(‘meta_key’, ‘assigned_lead’);
    $query->set(‘orderby’, ‘meta_value’);
    $query->set(‘order’, ‘ASC’);
    return;
    }
    }
    add_filter( ‘pre_get_posts’, ‘sort_by_date_my_cpt’, 1);

    Thank you!

  • The only thing stored for each post is the id of the related item. There isn’t any way to sort this by anything else unless you build a way to do it.

    For example, create an acf/save_post action that gets the user and saves another custom field value, not an ACF field, using update_postmeta() with a new field name to hold the value you want to sort posts by. Then you use this field in your query to sort the posts.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Sorting by relational linked user fields’ is closed to new replies.