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

Sorting and limitation with pre_get_posts

Before we code and go into particulars, lets look at the problem at hand.

  • First of all, any valid date format is valid in a custom field if you are not going to use it for comparisons and sorting

  • When you are going to sort by date or do comparisons by date in a custom field, bullet point one should be ignored. There are only two workable formats which will work if you are going to sort by custom field date. They are:

    • Unix Timestamp (which I prefer out of personal opinion) which is an integer value and corresponds to the amount of seconds passed since 1 January 1970. Saving a date in this format is the most accurate in my opinion, and any timestamp can be easily converted into any format using the DateTime class. Just a note, only dates between 01 January 1970 and 19 January 2038 are currently supported

    • Y-m-d H:i:s or Y-m-d or H:i:s. Any other format will not work. The orderby parameter sorts literally, so basically, the first number of the given strings are compared and sorted ascending or descending according to the order parameter, if they match, the second number is compared, etc until non matching numbers are found and the sort order is returned. It is recommended to set the correct type parameter value in your meta_query according to your specific format. These type parameter values are DATE, DATETIME and TIME which will handle your exact format when querying this particular fields

The above is very important, so before you continue, make sure that you understand that part and that your values is in the correct format, otherwise the next section will not work

Now that the format is sorted, we need to write down in plain English what we need. I tend to use this method if something gets tricky or too complex. It does help a lot. So, in plain English, this is what your query should do

All posts with thumbnails should be shown. This option is saved as a custom field, _thumbnail_id. In addition, these posts should also have dates in the future, to be exact, within the next thirty days. This is also according to a custom field. These posts should also be sorted according to the dates in the custom field

Great, so this means, in our meta_query, our posts should have a thumbnail AND (this will be our relation between the custom fields) and must have custom field date value BETWEEN the current time and 30 days from the current time

Lets put that into code: (Note: Caveat: This is untested and requires at least PHP 5.3 to work due to the use of DateInterval. Also, this is set up with the Y-m-d H:i:s date format in your custom field. Keep your date formats uniformly, otherwise it will not work)

add_action( 'pre_get_posts', function( $q )
{
    if (     $q->is_home() // Target the home page only
          && $q->is_main_query() // Target only the main query
          || $q->is_category() // NO IDEA WHY YOU ADDED THIS! ARE YOU TARGETING CATEGORY PAGES AS WELL?
    ) {

        $current_time = new DateTime(); // Get the current date and time
            $current_time_format = $current_time->format( 'Y-m-d H:i:s' ); // This is the current date and time

        $after_thirty_days = new DateTime(); // Create the date after 30 days
            $after_thirty_days->add( new DateInterval( 'P30D' ) ); // Adds 30 days to the current date and time
            $date_after_thirty_days = $after_thirty_days->format( 'Y-m-d H:i:s' );

        $meta_query = array(
            //Default relation is AND, no need to set it. So posts should match both conditions set in the two sets of arrays
            array( // Our first array of conditions set to get posts with a thumbnail
                'key' => '_thumbnail_id'
            ),
            array( // Our second array of conditions. Posts should also have these conditions in addition to the first array of conditions
                'key' => 'event_date',
                'value' => array( $current_time_format, $date_after_thirty_days ), // Add todays date and date after 30 days as an array
                'compare' => 'BETWEEN', // Will look for valid values between the array of dates given in the value parameter
                'type' => 'DATETIME' // We will use the date and time format to compare our dates
            ),
        );
        $q->set( 'meta_query', $meta_query );
        $q->set( 'orderby', 'meta_value_num' );
        $q->set( 'meta_key', 'event_date' );
        $q->set( 'order', 'ASC' );
    }
});

LAST FEW NOTES:

  • As I have noted before, this is untested, so it might not work straight out of the box. It may need some adjustments.

  • I have used the format Y-m-d H:i:s here. You can just use Y-m-d here as well. Just adjust the query and dates accordingly. If are going to use timestamps, remember to convert your comparison dates into timestamps

  • Because you are using infinite scrolling, you will need to remember to adjust that function accordingly, otherwise page 2 and up will display wrong posts

EDIT

The above code is now tested and work as expected with date formats of Y-m-d H:i:s and Y-m-d. I had to fix one or two small bugs. Hope it helps

Related Posts:

  1. How to hook a filter to catch get_post_meta when alternate a custom field output?
  2. How to use update_{$meta_type}_metadata filter to modify meta value
  3. How can I display image metadata?
  4. Search pre_get_posts filter which can handle multiple post types and categories?
  5. How to filter into post meta data before saving
  6. Explanation for remove_filter used in the below code [closed]
  7. Filter list by a unique meta value dilemma
  8. Search results sorted by post types
  9. Why anything done on comments_array hook gets reset?
  10. How to remove get_post_metadata using remove_filter inside a class?
  11. Filter Media by Featured on Admin
  12. Get .subsubsub count of post per status queried using pre_get_posts
  13. Remove posts inside pre_get_posts using a custom query
  14. Filter pre_get_posts does not modify Mine/All/Pending
  15. Custom wp_query time filter on meta_value
  16. Filter for author list in gutenberg core editor
  17. Filter posts by meta data using custom query
  18. Sorting products by price ( regular + sale price )
  19. get_posts() interrupt because of filter
  20. pre_get_posts to hide everywhere posts from “Archive” category
  21. Excluding posts by meta, and also keeping posts without the meta
  22. Drop down filter sort posts by latest, last 7 days and monthly
  23. Apply pre_get_posts filter in a certain moment (just for a particular block of posts)
  24. how to develop a filter in wordpress to let the user filter the page content depends on the date (newest to oldest etc…)?
  25. Testing requested query in pre_get_posts
  26. How to add more than one custom metadata as filter on the post list page?
  27. using posts_where for meta data on pre_get_posts
  28. Hide H1 Title using the_title filter
  29. Adding an orderby filter, casting postmeta with multiple keys
  30. Filter and Search
  31. Custom taxonomy with custom meta value is not sorting correctly (query returns the same value for orderby regardless of sort column click)
  32. posts_results filter – additional sort, with a meta value, to move posts to the end of the results, with pagination working
  33. Disable emojicons introduced with WP 4.2
  34. How to remove a filter that is an anonymous object?
  35. Can the Next/Prev Post links be ordered by menu order or by a meta key?
  36. Can I exclude a post by meta key using pre_get_posts function?
  37. WordPress hooks/filters insert before content or after title
  38. How to add defer=”defer” tag in plugin javascripts?
  39. add_action(), add_filter() before or after function
  40. apply_filters(‘the_content’, $content) vs do_shortcode($content)
  41. How do filters and hooks really work in PHP
  42. Trouble understanding apply_filters()
  43. What is the very earliest action hook you can call?
  44. How would one modify the filtering Gutenberg applies to pasted content?
  45. How can I modify the WordPress default widget output?
  46. Add custom options to the wplink dialog
  47. Remove classes from body_class
  48. what is __return_false in filters
  49. Explanation for apply_filters function and its variables
  50. Gutenberg: Is there a way to know if current block is inside InnerBlocks?
  51. How to reorder billing fields in WooCommerce Checkout template? [closed]
  52. Insert HTML just after tag
  53. the_content and is_main_query
  54. Changing WooCommerce Display Price Based on User Role & Category [closed]
  55. How to add a custom CSS class to core blocks in Gutenberg editor?
  56. How to show page content in feed?
  57. wp_headers vs send_headers. When to use each?
  58. Filter any HTTP request URI?
  59. How to Pass External Variables to Filters/Actions
  60. How to filter users on admin users page by custom meta field?
  61. Filter by one custom field, order by another?
  62. Use REGEXP in WP_Query meta_query key
  63. How to Change Order of Posts in Admin?
  64. Not able to change wp_title using add_filter
  65. Orderby meta_value only returns posts that have existing meta_key
  66. How to appending to the_content using add_filter with custom post type?
  67. Query WP REST API v2 by multiple meta keys
  68. No filter of code on switch from html to visual editor, how?
  69. Sanitize and data validation with apply_filters() function
  70. How to modify posts_where filter only for the search query
  71. How to get shortcode’s input values inside a filter?
  72. Removing Image and Caption Dimension Attributes
  73. How to wrap oEmbed-embedded video in DIV tags inside the_content?
  74. How to bulk delete all users with no posts?
  75. How many filter/action hooks are healthy?
  76. WordPress 3.9 – Trouble Editing TinyMCE 4.0
  77. Changing JPEG compression depending on image size
  78. How to add filter with 2 args?
  79. Why is javascript allowed in my post content?
  80. How to wrap an element around an iframe or embed in content automatically?
  81. Filter specific shortcode output?
  82. WordPress Internal @ Mentions
  83. How to add headers to outgoing email?
  84. Earliest hook to reliably get $post/$posts
  85. Insert new element to array with add_filter
  86. LESS CSS enqueue_style with add_filter to change rel attribute
  87. Is it possible to filter comments in a post so a user can only see the comments they have written?
  88. How to pass/get data to/from the WooCommerce data-product_variations object?
  89. Remove Editor From Homepage
  90. How to modify Contact Form 7 Success/Error Response Output [closed]
  91. Where to hook into post content?
  92. What does (10, 2) mean when used with add_filter
  93. Filter translations (gettext strings) on specific admin pages
  94. Filter username field on registration for profanity and unwanted words
  95. Clarification on filters and hooks
  96. sort child pages on admin
  97. remove_filter( ‘the_content’, ‘wpautop’ ); only for certain post types
  98. At what priority does add_filter overwrite core functions?
  99. Custom Table Column Sortable by Taxonomy Query
  100. Custom search filter causes menu and query_posts problems
Categories filters Tags filters, post-meta, pre-get-posts, sort
how to incude logo in contcat form 7 email [closed]
Is there a way to connect a custom post type to another custom post type’s taxonomy? (specific to locations)

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