Support

Account

Home Forums ACF PRO Exclude Posts by Date

Solved

Exclude Posts by Date

  • Hi

    I have a loop that displays posts from two post types, one the default posts and the other a custom post type for events.

    I’m trying to exclude posts which have a date which is past today, old events.

    I’m using the following which works to exclude the posts by the past date but it will only show posts from the custom post type ‘Events’ and not the default posts. I feel like I’m missing something really stupid.

    Thanks

    $today = date('Ymd');
    	query_posts(array(
    		'post_type' => array( 'post', 'events'),
    		'showposts' => 20,
    		'meta_query' => array (
    		       'post__not_in' => array (
    			'key' => 'event_date',
    			'value' => $today,
    			'compare' => '>='
    			)
    		)
    	)
    );
    
  • I’m a little surprised that works at all because you can’t nest post__not_in inside of meta_query.

    Do the standard “Posts” also have the date field? I’m assuming that this is not the case. If it is, then you’re query will not return any “posts” because that meta value is not set.

    What you need to do is a query on your events to get the list of posts that you don’t want to include

    
    $today = date('Ymd');
    $args = array(
      'post_type' => 'events',
      'posts_per_page' => -1,
      'meta_query' => array(
        array(
          'key' => 'event_date',
          'value' => $today,
          'compare' => '<'
        )
      )
    );
    $old_events = new WP_Query($args);
    $post__not_in = array();
    if ($old_events->have_posts()) {
      $post__not_in = wp_list_pluck($old_events->posts, 'ID');
    }
    

    now you can use what you code from the above for post__no_in

    
    query_posts(array(
      'post_type' => array('post','events'),
      'showposts' => 20,
      'post__not_in' => $post__not_in,
    ));
    
  • Thanks so much! Perfect!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Exclude Posts by Date’ is closed to new replies.