0

I'm using WordPress as a searchable database of people, and I want to be able to sort search results by the person's last name. Initially, I figured I could sort the search results in just alpha, but it results in sorting them in alpha by their first name.

So I figured if I create a backend-only custom field for the person's last name, I could adjust the search result to display based on the custom field but in alpha order. I would want all search results to follow these rules.

Does this make sense, or is there an easier method I could try? I know I could do this with a plugin, but I would rather avoid using a plugin for such an integral part of what we need this to be. Plus, I want to know how it works so I can fix it if something breaks. haha.

This is the code I have been working from-it gets me the alpha part, but I don't know how to apply the custom field.

function abc_search( $query ) {
    if( $query->is_search ) {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
    }
}
add_filter( 'pre_get_posts','abc_search' );

1 Answer 1

0

Surname is already stored as user meta last_name so you don't need a custom field. You do need to make sure you're only affecting the page you want to.

    function sort_users_by_lastname( $query ) {
        // only if we're on users.php
        // and when orderby isn't changed. the default (when nothing is set) is "login"
        $screen = get_current_screen();
        if ( $screen->base == 'users' && is_admin() && $query->get('orderby') === 'login') {

            // Set the orderby parameter to user's last name
            $query->set( 'meta_key', 'last_name' );
            $query->set( 'orderby', 'meta_value' );
            $query->set( 'order', 'ASC' );
        }
    }
    add_action( 'pre_get_users', 'sort_users_by_lastname' );
2
  • Thank you for the response! I appreciate the help. Unfortunately, we didn't want to go the user route and made each entry as a custom post type. I wouldn't have access to the surname option with the route we decided to go with. Would I be able to add more items to this line "$query->set( 'meta_key', 'last_name' );" that addresses the custom content field?
    – user231567
    Commented Apr 13, 2023 at 18:33
  • I figued out the code and I got it work: function abc_search( $query ) { if( $query->is_search ) { $query->set( 'meta_key', 'expert_last_name' ); $query->set( 'orderby', 'meta_value' ); $query->set( 'order', 'ASC' ); } } add_filter( 'pre_get_posts','abc_search' );
    – user231567
    Commented Apr 13, 2023 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.