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 posts by meta value on posts page

So I figured out how to get what I want, but it’s still not perfect.
The problem revolved around how my custom meta value was being stored – basically as a string.

I needed to tell MySQL that it was a date, so it could be used to order the posts. To this end, I used a custom query:

    $posts = $wpdb->get_results( 
       "SELECT wp_posts.*, 
        STR_TO_DATE(m.meta_value, '%Y-%m-%d') AS m_date 
        FROM wp_posts 
        LEFFT JOIN wp_postmeta AS m ON(wp_posts.ID=m.post_id AND m.meta_key='date')
        WHERE post_status="publish" AND post_type="post"
        ORDER BY m_date DESC"
);

if ($posts):
    global $post;
    foreach ($posts as $post):
        setup_postdata($post);
        echo get_the_title(); //finally in the right order!
    endforeach;
endif;

This uses the MySQL function STR_TO_DATE() to cast the meta value as a date, then use it to order the posts in the ORDER BY clause.

So this is all well and good but it would be much better if I could hook into the query before it’s run and alter the SQL just this little bit, I could make a big saving in terms of queries. The site is a small one so it’s not a massive concern, but every little helps.

If someone knows how to do that, I’d happily accept that answer instead of my own.

References:

http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date

Related Posts:

  1. Order by meta value or date?
  2. Filtering posts by post meta data
  3. query_posts doesn’t order by title
  4. Custom query with query_posts doesn’t show post without certain meta_key
  5. How to sort by meta value?
  6. get_post_meta causes database queries
  7. Order by meta_key with two meta_queries
  8. Ordering terms before displaying posts
  9. Querying posts with meta value that begins with a certain pattern
  10. orderby:date not working
  11. WordPress query_posts and orderby page order
  12. IF.. post meta show… Conditional Tag Help…?
  13. Order posts by condition
  14. Query_post($args)
  15. query_posts() on key’s value, or key’s existence
  16. How to retrieve an array of post IDs by a particular value stored in a custom meta’s array
  17. Sorting a query Field by date
  18. Query posts by meta_key whose value is an array
  19. define orderby URL with meta_key=post_views_count
  20. Exclude posts by post meta value
  21. Frontend form with multiple posts
  22. WordPress query reverse order
  23. query_posts orderby postmeta [closed]
  24. Ordering Posts By Meta Data
  25. Order posts by ACF checkbox
  26. orderby not working for query_posts using array of IDs
  27. get all posts with certain meta data
  28. Limiting the amount of posts this displays
  29. How to Get All Posts with any post status?
  30. posts_per_page no limit
  31. what is the correct way to compare dates in a WP query_posts meta_query
  32. How can i get count from query post
  33. query_post by title?
  34. Why query_posts() isn’t marked as deprecated?
  35. Alternative to query_posts for main loop? [duplicate]
  36. how to query posts by category and tag?
  37. Using WP_Query to Query Multiple Categories with Limited Posts Per Category?
  38. How do I query by post format in WordPress 3.1
  39. Display posts of the last 7 days
  40. Is there a way to exclude the content from the post variable to save on RAM usage?
  41. Order by optional meta key?
  42. How to query_posts using meta_query to orderby meta_key AND have a secondary sort by date?
  43. Query posts by custom taxonomy ID
  44. Display/query post formats
  45. Order by & include array by specific post ids
  46. How to query post by user role?
  47. How to return results of a get_posts() in explicitly defined order
  48. Query Posts in a Predefined Order
  49. Help to condense/optimize some working code
  50. Order posts by ID in the given order
  51. How to set posts per page using WP_Query()
  52. query_posts exclude a meta key
  53. How do I create a random post that will last for a day
  54. Ensuring sticky posts are retrieved first (without using two queries)?
  55. Determine if more posts are available than was asked for in `query_posts()`?
  56. Modify main WordPress loop with a parse_query filter
  57. Ordering posts having multiple post-meta date fields
  58. query_posts() in function makes global $wp_query out of sync?
  59. Limiting query_posts to 1, regardless of sticky post?
  60. How to make “sticky” pages (and query by them)
  61. Query posts: how to exclude results if post is in multiple categories
  62. Query Custom Meta Value with Increment
  63. query_posts ->using meta_compare / where meta value is smaller or greater or equals
  64. Problem with ‘post__not_in’
  65. How to order posts by descending comment count on taxonomy page?
  66. Sort posts alphabetically by custom field value, insert divider between different letters
  67. Is it better practice to use query_posts, WP_Query, or get_posts to create various custom loops within a Page?
  68. WP 5.8 “Query Loop” block: where to place custom query?
  69. WP_Query ordered by custom field that is a date string?
  70. Sort X categories by last update and show image
  71. Custom Post Type “Event”: chronological list of recurring events
  72. Meta query interfering with orderby relevance
  73. using post__in allow duplicate post id
  74. Pagination on archive.php page
  75. WordPress Custom Query
  76. Best way to load page content in Fancybox popup?
  77. How should I intercept the main query and inject custom join / order by / group by criteria
  78. advice on creating a ‘related posts’ query like the one used on stackexchange
  79. order post my meta value m/d/y format with year as included value
  80. Order by meta value, pro first, then free
  81. Having trouble generating pagination links on custom query
  82. How to create an attachments archive with working pagination?
  83. _wp_page_template to dynamically use template
  84. Using dynamic conditions in ‘posts_where’ filter
  85. Compare 3 custom fields and sort by oldest
  86. Help altering a query to exclude all but standard post format
  87. List users with the most total posts view
  88. Schedule Sticky Posts
  89. Use union/intersection query_posts variables in uri request parameter form?
  90. How to limit search to first letter of title?
  91. query_posts and pagination, still stuck after much research
  92. Query posts by taxonomy term name
  93. Sorting problem with ‘query_posts’ funcion in wordpress. Sort by custom field not working
  94. Total Count of Posts NOT in Selected Categories?
  95. how could I get the pagination as I want to when query posts using get_posts function
  96. Counter code for paginated category pages in wordpress
  97. Post Title displaying but not in the wrapped HTML I need
  98. Author List page: Exclude based on last post date
  99. WordPress Search Filter Only for Page with Child of Child of Child of Child of Child
  100. Ordering posts by anniversary using only day and month
Categories query-posts Tags order, post-meta, query-posts
Editing a list of several fields
Cant remove line that appears above page content

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