database – Order of search results based off of a backend custom field and also in alpha order


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’ );

Any chance I can get help with this?

user231567 2 months 2023-04-12T17:57:25-05:00 0 Answers 0 views 0

Leave an answer