0

I have written a filter to be called in pre_get_posts to remove posts from a category page based on a meta_key (EventDate which is in the form YYYYMMDD), which is working.

However I'm struggling with the next step, which is to change the category of the now excluded post. Does anyone have any suggestions on how to get this working?

I have tried:

function pre_get_posts_filter($query){
    if($query->is_main_query()){
        if(is_archive()):
            if(is_category($category='Events')):
                $a=array();
                if(get_post_meta(get_the_ID(),$key='EventDate',$single=true)<date('Ymd')):
                    $query->set('post__not_in', array_push($a,get_the_ID()));
                    wp_set_post_categories(get_the_ID(),array('PastEvents'));
                 else:
                   //Set the order ASC or DESC
                   $query->set( 'order', 'ASC' );
                   //Set the orderby
                   $query->set( 'orderby', 'meta_value_num');
                   $query->set('meta_key', 'EventDate');
                endif;
            endif;
        endif; 
        return $query;
    }
    };

Any help would be greatly appreciated. Thanks

  • 3
    You can't do this at this stage. The posts haven't been queried yet (pre_get_posts after all), so there's no post to set the category on. If you want to change the category of 'expired' posts then that's something best done as part of a recurring background event, not as part of the query for a category archive. – Jacob Peattie Jan 16 at 14:07
  • 1
    @JacobPeattie Thanks for the quick reply. That would definitely explain why it wouldn't work! Time to look at wordpress cron jobs. – Jon Jan 16 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.