Sometimes, we want to query the database for based on some custom fields we have set. With WordPress you can achieve this easily.
Let say, you have a date field for the event post type and you want to get all the records which are going to end today or in future.
$now = new DateTime(current_time('mysql')); $args = array( 'post_type' => 'event', 'meta_query' => array( array( 'key' => 'start_date_time', 'value' => $now->format('Y-m-d H:i:s'), 'compare' => '>=', 'type' => 'DATETIME' ) ) ); $query = new WP_Query($args); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ...Your code here... endwhile; endif;
Querying in WordPress sometimes really gets complicated. Hopefully, with the above example it makes it easy for you to understand how things work. Leave a comment below for any suggestions to further improve the above concept.