ACF Wordpress插件 - 按日期字段排序

时间:2014-04-26 20:00:29

标签: wordpress advanced-custom-fields

我正在使用高级自定义字段插件在帖子中创建活动日期。我想在该日期之前订购我的帖子,并且还只显示一个类别的帖子。我在他们的网站上关于日期字段的文档,但它不起作用 - 它显示所有类别的帖子,它们按发布日期而不是事件日期排序。文档在这里:http://www.advancedcustomfields.com/resources/field-types/date-picker/ 我没有改变默认日期格式。 有谁熟悉这个插件?也许我的循环代码错了?我在文档中注意到他们使用'foreach'更简单的结构,而不是query_posts和while。

/*
*  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; ?>

1 个答案:

答案 0 :(得分:1)

您的代码运行不正常,因为它同时使用get_posts()query_posts()函数。 但是,对于您的自定义查询,我建议您使用WP_Query对象(请参阅Codex)。

试试这个:

<?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();
?>