Site icon Hip-Hop Website Design and Development

Order category posts by last word of custom field

I’m trying to order a category page by the last word of a custom field that all of its posts have. The custom field represents a name, so the last word would be the last name. In the end, the posts of the category page should be listed in alpha order by last name.

How do I achieve this?

Threads I’m looking at:

My code:

function sort_research_cycles_by_last_name($query) {
    $isResearchCategory = current_cat_is_sub_of(get_category_by_slug('research-cycles')->term_id) || current_cat_is_sub_of(get_category_by_slug('profile-expert-fr')->term_id);
    if ($isResearchCategory && $query->is_main_query()) {
        /*
         * Uncommenting the following two lines and setting orderby to $orderby
         * results in an odd order that I can't make sense of.
         */
        // global $wpdb;
        // $orderby = "SUBSTRING_INDEX($wpdb->postmeta.meta_key, ' ', -1)";
        
        /*
         * This currently only orders posts by alpha order of the first word
         */
        $query->set('meta_key','wpcf-name-of-researcher');
        $query->set('orderby','meta_value');
        $query->set('order','ASC');
    }
}
add_action('pre_get_posts','sort_research_cycles_by_last_name');