Question

I am using Advanced custom Fields plugin to create an event date in a post. I would like to order my posts by that date, and also show only posts from one category. I followed documentation on their site regarding the date field, but it doesn't work - it displays posts from all categories and they are ordered by the published date, not the event date. documentation is here: http://www.advancedcustomfields.com/resources/field-types/date-picker/ I haven;t changed default date formatting. Anyone familiar with this plugin? Is maybe my loop code wrong? I noticed in the documentation they use 'foreach' simpler structure, not the query_posts and while one.

/*
*  Order Posts based on Date Picker value
*  this example expects the value to be saved in the format: yymmdd (JS) = Ymd (PHP)
*/

$posts = get_posts(array(
    'meta_key' => 'event_date', // name of custom field
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'cat' => '23'

));?>

    <?php if (query_posts($posts)) : while (have_posts()) : the_post(); ?>

        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

            <div class="entry">
                <?php the_post_thumbnail( 'whatson-thumb' ); ?>
                <h2 class="pagetitle"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
                <?php include (TEMPLATEPATH . '/inc/meta.php' ); ?>
                <?php the_excerpt(); ?> 

            </div>
        </div>

    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>
    <?php else : ?>
        <h2>Not Found</h2>
    <?php endif; ?>
Was it helpful?

Solution

Your code isn't working well because it uses both get_posts() and query_posts() functions. However, for your custom query I suggest using the WP_Query object (read more in Codex).

Try this:

<?php
$args = array(
   'meta_key' => 'event_date', // name of custom field
   'orderby' => 'meta_value_num',
   'order' => 'ASC',
   'cat' => '23' 
);
$event_query = new WP_Query( $args );

// The Loop
if ( $event_query->have_posts() ) {

     while ( $event_query->have_posts() ) {
        $event_query->the_post(); ?>

        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

        <div class="entry">
            <?php the_post_thumbnail( 'whatson-thumb' ); ?>
            <h2 class="pagetitle">
                <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
            </h2>
            <?php include (TEMPLATEPATH . '/inc/meta.php' ); ?>
            <?php the_excerpt(); ?> 
        </div>

        </div>
    <?php
    }

}else{
    echo '<h2>Not Found</h2>';
}

// Restore original Post Data
wp_reset_postdata();
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top