0

I'm trying to use WP_query with a custom field to make one category of posts behave differently than the others; namely to 1) sort in ascending order by the custom date field (event_date) and 2) display only if event_date is today or in the future.

I've modified the code in the loop of the page.php file (on a test site, Twenty Fifteen theme) to loop twice - once for the single post category and once for all other post categories - but it seems there is something wrong in the date comparison and the post display has not changed since I started trying this (many hours ago).

Any help would be appreciated. Thanks.

    <?php
        // Start the loop.
    // custom 
    $today = date('Y-m-d');
    $today = strtotime( $today );
    $args = array( 
          'post_type' => 'post',
          'cat'   => '2',        
          'meta_key'    => 'event_date',  
          'order_by'        => 'event_date',
      'ignore_sticky_posts' => 1,
          'order'       => 'ASC',         
          'meta_query'  => array(
             array(         
              'key'     => 'event_date',  
              'value'   => $today,  
              'compare' => '>=',          
              'type'    => 'NUMERIC'         
            ) // 
           ) // 
          ); // 

    $the_query = new WP_Query( $args );
    // this is the loop below
    if ( $the_query->have_posts() ) {

        while ( $the_query->have_posts() ) : $the_query->the_post(); 

            // Include the page content template.
            get_template_part( 'content', 'page' );

    // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;

   // Get the custom field
   $post_date = get('date');
   $post_date = strtotime( $post_date );

   // If older than current date, don't show it
        if( $post_date < $today ):
        endif;
        // End the loop
        endwhile;

    wp_reset_postdata();
    }
    ?>
    <?php
    $args = array( 'cat'   => '-2'  );
    $the_query2 = new WP_Query( $args2 );
    // this is the second loop
    if ( $the_query2->have_posts() ) {

    while ( $the_query2->have_posts() ) : $the_query2->the_post(); 
    // Include the page content template.
            get_template_part( 'content', 'page' );

            // If comments are open or we have at least one comment, load up the     comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;
    endwhile;
    }
    ?>

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.