Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Order category posts by last word of custom field

but I’m not using a WP_Query since I’m just changing the order of a category.php page (so, correct me if I’m wrong, but WP_Query shouldn’t be necessary in that case, correct?).

Yes, you are. The whole point of the pre_get_posts action is to give you access to the query object before it goes to the database to change the parameters. That $query variable is a WP_Query object, and your code could be type-hinted like this:

function sort_research_cycles_by_last_name( \WP_Query $query) {

In fact the answer linked to there is the closest I’ve seen to what needs doing in the SQL section written below.

which covers everything except how to order by the last word of the meta key.

That’s because this is not possible using WP_Query out of the box. You will need to extract the last name into a separate field, or re-order the name so that the last name appears first, e.g. Nowell Tom instead of Tom Nowell.

You can query post meta values based on wether they exist, their type, their value (full value, not sub-sections), you can even query for the existence of sub-strings of their value e.g. find all meta that contains XYZ. You can’t order by sub-sections though, whatever comparison you make applies to the entire value.

The official docs outline these as the parameters:

meta_compare (string) – Operator to test the ‘meta_value‘. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘NOT EXISTS’, ‘REGEXP’, ‘NOT REGEXP’ or ‘RLIKE’. Default value is ‘=’.

from https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters.

REGEXP is the closest to what you want but that only gets you as far as “does it end with a word that comes after a space yes or no?”. As far as sorting goes, this would put all the people who fit that at the end, or at the start, but no alphabetic sorting within those 2 groups, just a haves/have nots. This is useful for filtering, but not sorting.

Raw SQL, the Unreliable Ultra Hard option

It might be possible with raw SQL, but the results will be highly unreliable, and the SQL would be broken by other plugins. As I mentioned in my comment, not all people have surnames, not all surnames are a single word, some people have titles after their surname or other indicators. Double barrel surnames or surnames with spaces in particular will be problematic, and are more common than people realise, e.g. de Sousa.

If you chose to go down this route, it would be much more difficult than using a separate meta key. The query to extract the last word would be similar to this in its most generic form as a SELECT:

SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,-1) as anyVariableName from yourTableName;

You would need to figure out the full list of SQL filters, then build a check to identify only your query that needs this sorting, then, parse and rebuild the query so that it rewrote the sorting section.

You might need to create an additional query to do this, and this query will be slow and expensive. Expect a major performance hit. Also expect issues with other plugins that also try to modify the posts SQL query.

You will also need to figure out how to handle names that have trailing spaces, as this will result in an empty last field when used with your heuristic

This solution is the most time consuming, it would be easier and faster to manually update each entry by hand.

Using a Last name Meta

The real solution is to use first_name and last_name fields, combined with a display name field. This way you know both first and last names but can also account for decoratives, signifiers, postfixes, titles, middle names, etc. For example my own name Tom J Nowell does not fit into the first/last name pattern. This is also what WordPress itself does.

If necessary, you can solve this by doing a WP_Query for all users that do not have the last_name meta key, then grabbing and saving the first/last names as separate keys. Do this in batches of 50 to avoid timeouts. When all posts are processed then it will naturally find no new posts to process and the job is done. Update your site elsewhere to let users update these values in the existing forms, and the job is done.

As a bonus, having first/last names allows you to give users the option to sort using both. This is a common feature in contact applications, as there’s significant cultural and regional variation. It also allows you to do sub-sorting of people who have the same last name.

Related Posts:

  1. Define category ID using get_post_meta
  2. Add a “custom field” to a category that can be retrieved when viewing the category page with get_post_meta
  3. How to update custom fields using the wp_insert_post() function?
  4. How to display multiple Post meta_key/meta_values by SQL query
  5. How to use multiple query with same meta key
  6. Add custom field to attachments in a specific category
  7. How can update custom meta for all posts
  8. Use ajax to update_post_meta
  9. how to increase custom post value by one most efficiently?
  10. How can I create a list of page titles from custom meta values?
  11. Store multiple custom field as post meta per post(css, js, html, 2 link) [closed]
  12. How to VAR_DUMP a $variable during checkout process (Is my product meta callable?)
  13. Is it possible to retrieve all posts with a certain value for metadata?
  14. Non-Closing PHP Query in WordPress Loop
  15. how to get serialized post meta
  16. WordPress loop by meta key that is an array? and how loop multiple arrays
  17. How to store multiple custom meta box
  18. Order a WP_Query by meta value where the value is an array
  19. Add a custom class to the body tag using custom fields
  20. Hide a div when a custom field is empty
  21. WordPress stripping out custom field tags
  22. How to update custom fields when post is published?
  23. WP post meta – for loop inside for loop
  24. When working with a post, almost all wp_postmeta are deleted
  25. Updating Lat and Lng of posts automatically gives sporadic results
  26. If custom field doesn’t exist, or exists and it’s true show title?
  27. Metadata on the WP_Post object
  28. Importing hard coded custom field into acf field
  29. hover image appears below placeholder instead of overlayed
  30. combine Code 1 with Code 2
  31. Get Current User Id Inside a Loop Returns 0 For a Shortcode
  32. get current product name in functions.php
  33. Random order of WP_Query results with highest meta value
  34. tracking number field in Woocommerce order [closed]
  35. get post based on category chosen in drop down – The ajax method
  36. How to use transient in this code for related post?
  37. Creating a related post section based on similar categories
  38. Swapping wp_dropdown_categories function with wp_category_checklist
  39. The text box have space character
  40. how to remove metadata from the posts of my blog?
  41. Trying to remove post thumbnail with plugin
  42. Randomly Assign an Image’s Alt Text Based on Data From Post
  43. Passing the custom field values in the wp_get_current_user array function
  44. Advanced Meta Query for Large Calendar Website (12k+ posts) (175k+ wp_postmeta rows)
  45. Sort posts by custom fields value using dropdown menu
  46. Proper syntax or method for keeping url in modified isotope / category links
  47. Custom profile field with birthday. Troubles with
  48. Filter Select results based on selection
  49. query in category.php repeats itself
  50. WordPress – Display array data of a child
  51. What is an equivalent of single_cat_title for getting the slug of the category?
  52. Issue adding sub category programmatically
  53. Assign / update custom field value for all posts (How can I assign only to posts without custom field value?)
  54. wordpress allow user to edit user profile with custom fields
  55. Why do WP_Query results change after updating unrelated Advanced Custom Fields (ACF)?
  56. How to exclude category ID from Looper in WordPress
  57. Add a specific part of current category page url to shortcode
  58. how do I get a specific post from a post with a subcategory in WP
  59. Sort custom meta column by other meta value
  60. WP grandchild categories in nested ul li
  61. Grab posts by multiple categories
  62. Pass Category Name, Description and Photo into variables to pass to jQuery
  63. How to show single category archive
  64. Move category description below post list in blog
  65. Creating user status mode in WordPress
  66. Need Help Fixing My Iframes [closed]
  67. How to pick the default selected value in wordpress dropdown?
  68. get_post_meta not working on publishing
  69. Need help with Google drive API [closed]
  70. Firing schema via code in functions.php doesn’t work
  71. Applying A Category to Existing Posts Where Page Title Matches Regex
  72. Get page that displays all children of taxonomy parent
  73. Adding number to date not working [closed]
  74. How can I add extra word in permalink when someone click download button?
  75. Saving and Restoring a Canvas on A Individual User Basis
  76. selected option if current category is the value
  77. Seach custom post type posts only by meta fields?
  78. How to use thumbnail size of image if I’m only using src to get image
  79. 3 Slashes appear after Apostrophe in custom fields after updating product-site
  80. get_template_part based upon post’s category
  81. how to retrieve a value if a checkbox is checked
  82. how to save selected option in variable for rest api category filter
  83. Trouble checking if custom woocommerce checkout field is empty or not
  84. Two queries for a WP_User_Query search work perfectly apart, but not together
  85. Setting default category base on theme activation
  86. Recent Posts Not Showing Only On A Specific Category Page [closed]
  87. Hide subcategories (widget)
  88. Alert Bar section within WP loop is displaying even though there are no posts
  89. Let Users Choose Post Categories
  90. Archive post by meta value + 24hours
  91. Different post styles depending on category
  92. Display category name only once inside loop
  93. auto-populating custom nav with all items from custom post type
  94. Add / Update Custom Fields After Select Pictures in Media Window
  95. WordPress update_post_meta updating with empty meta_value field [closed]
  96. conditional logic for front-end custom field edits
  97. How to show only subcategories in parent category not parent category?
  98. Trying to retrieve post meta
  99. Automatic Shortcode Creation with Custom Fields [closed]
  100. Custom field values to taxonomy terms
Categories PHP Tags categories, custom-field, php, post-meta
Redirect to new domain that serves new and different content
Merge CPT Taxonomy and Post Taxonomy in $query->set

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress