• Hello,

    Im having really hard time with one custom query and any help will be appreciated.So the story – my query is limiting front page posts to only those which have featured images. So far so good. My last goal is to sort those posts by custom field, order them in ASC order and show only posts which metakey/custom field date is in 30 days from now.

    Current sorting is chaotic. For the second part showing only posts in the next 30 days what I have in mind is to set one var holding current date + 30 days, one var with custom field date and to check is the first one bigger than the second one but how I can get the custom field in this function and where to put this if check ? Probably these question are simple but Im struggling. Thank you for your time and for sharing knowledge.

    So far this is my code along with my attempts but as it seems Im not even close…

    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()
        ) {
            $meta_query = array(
                array(
                    'key' => '_thumbnail_id',
                )
            );
            $q->set( 'meta_query', $meta_query );
            $q->set('orderby','meta_value_num');
    $q->set('meta_key', 'event_date');
    $q->set('order', 'ASC');
        }
    });
  • The topic ‘Sorting and limitation with pre_get_posts with custom field’ is closed to new replies.