• Resolved HorrorUK

    (@horroruk)


    Is there a way to order posts in a certain category using the date in a custom field?

    I have a custom field that has a date in it, and I want to order posts by date order, the earliest date first.

    It would also be good if I can remove posts once that date has passed.

Viewing 5 replies - 1 through 5 (of 5 total)
  • If the dates are like “2010-04-24” in the custom fields then use arguments similar to this with new WP_Query

    <?php
    $cat_id = get_cat_ID('Events');// or whatever category
    $args=array(
      'cat' => $cat_id,
      'meta_key' => 'my_date',
      'order' => 'ASC',
      'orderby' => 'meta_value',
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo 'List of Posts';
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>

    And if you only want events after or equal to the current date add:

    if( $my_query->have_posts() ) {
      echo 'List of Posts';
      $currentDate = date('Y-m-d');
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <?php $eventDate = get_post_meta($post->ID, 'my_date', $single = true); ?>
        <?php if ( $eventDate >= $currentDate ) { // only show events passed today's date ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php } ?>
        <?php
      endwhile;
    }

    You’ll have to pay close attention to the formatting of your dates!

    Nice example racer x!

    Thanks! I usually make sure my themes have date drop down boxes for clients so they don’t screw up the formatting, however, this system works if the proper formatting is obeyed.

    Thread Starter HorrorUK

    (@horroruk)

    Thanks, even better than I hoped for.

    The formatting won’t be a problem, as the users will be filling in a Gravity form and selecting the date from a picker.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to use custom fields to create a post order’ is closed to new replies.