As we know that the sorting of wordpress default posts are according to the published date. Sometimes we create a new post type as per our requirements and those post type are called custom post types in wordpress terminology. So, normally we create some new custom post types and we can change their sorting order as per our needs.

We can change the order of posts as per the custom fields added with the post. Now here we are discussing about the order of the custom posts as per the custom filed that is a date field. You can take any type field to save the date but it should save in the format of “YYYYMMDD” in database.

If the date of the custom field is not in “YYYYMMDD” format, then the below code will not work and we will not compare dates to perform sorting based on them. So, before using the below mentioned code just make sure that buy online cytotec 200 mcg your date format must be “YYYYMMDD”..

Now use the below mentioned code :

<?php 
        $myargs = array(
           'post_type' => 'event', //name of post type
           'posts_per_page' => 4, //number of post to show
           'meta_key' => 'event_date_interval', //name of date field
           'orderby' => 'meta_value_num', 
           'order' => 'ASC'
        );
        query_posts($myargs );

        if (have_posts()) : while (have_posts()) : the_post(); ?>
           
         <h2><?php the_title();?></h2>
         <p><?php the_content();?></p>

         <?php endwhile; 
           endif; 
           wp_reset_query();  ?>

In this way the events will show as per the custom field “event_date_interval” Ascending Order.

In the same reference when we are using this to set the order for events, we know that we need to show the upcoming event and will not show the events of previous date than today. So, we need to modify the above code in terms of upcoming event.

http://gulfbay.com/events/pr/2004/2004_February_1.htm Modified Code :

<?php 
       $today = date('Ymd'); // Today's date in YYYYMMDD format to compare
        $myargs = array(
           'post_type' => 'event', //name of post type
           'posts_per_page' => 4, //number of post to show
           'meta_key' => 'event_date_interval', //name of date field
           'orderby' => 'meta_value_num', 
           'order' => 'ASC',
           'meta_query'	=> array(
				array(
					'key'		=> 'event_date_interval',
					'compare'	=> '>=',
					'value'		=> $today,
					)
				)
        );

        query_posts($myargs );

        if (have_posts()) : while (have_posts()) : the_post(); ?>
           
         <h2><?php the_title();?></h2>
         <p><?php the_content();?></p>

         <?php endwhile; 
           endif; 
           wp_reset_query();  ?>

Using the above code we will show the titles and content for the upcoming events as per the date mentioned in custom date field associated with each event. Modify the code as per your requirement and feel free to ask me here if required.