简体   繁体   中英

PHP: Doing while loop if “if” statement is true

I am trying to show only those events, which are in current date or in future. To show events I have such code:

<?php 
    $wp_query = new WP_Query();
    global $more;
    // set $more to 0 in order to only get the first part of the post
    $more = 0; 
    $wp_query->query( array( 'post_type' => 'events', 'posts_per_page' => 7, 'paged' => $paged, 'orderby' => 'menu_order', 'order' => 'ASC') );

    while ( ($wp_query->have_posts()) ): $wp_query->the_post();
        get_template_part( 'content', 'event' );
    endwhile;
?>

I tried to add "IF statement" to compare event start date with current date, but it doesn't seem to work. I have tried a lots of versions, but this one I think should work:

 $wp_query->query( array( 'post_type' => 'events', 'posts_per_page' => 7, 'paged' => $paged, 'orderby' => 'menu_order', 'order' => 'ASC') );
 $OstartDate = get_post_meta($post->ID, '_event_start', TRUE);
 $today = date('d.m.Y');
 while ( ($wp_query->have_posts()) && ($OstarDate < $today) ): 
      $wp_query->the_post();

From the second one you should try,

$OstartDate=get_post_meta($post->ID,'_event_start',TRUE);//check it will return a number
if(time() > $OstartDate)
{
   while ($wp_query->have_posts()):
      $wp_query->the_post();
   .....
}

a7-simple-events may help you.

You can compare the posts with postmeta using meta_query

$today = date('d.m.Y');
 $args=array( 'post_type' => 'events', 'posts_per_page' => 7, 'paged' => $paged, 'orderby' => 'menu_order', 'order' => 'ASC', 'meta_query'            => array(
        array(
            'key' => '_event_start',
            'value' => $today,
            'type' => 'date',
            'compare' => '<'
        )
    )) ;
    $wp_query = new WP_Query( $args );

 while ( ($wp_query->have_posts())  ): 
      $wp_query->the_post();
      endwhile;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM