高级自定义字段中的发布对象按日期排序
问题描述:
嗨我有一个高级自定义字段中的发布对象字段,我想返回多个帖子,按日期排序。我有这些帖子的自定义字段数据正常返回,但帖子对象按帖子ID的顺序返回。我希望他们可以在帖子发布之日起订购。高级自定义字段中的发布对象按日期排序
<?php $post_objects = get_field('exhibitions');
if($post_objects): ?>
<?php foreach($post_objects as $post_object): ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<div style="display: inline-block">
<? if(get_field('title', $post_object->ID)): ?>
<em><?php the_field('title', $post_object->ID); ?></em><br>
<?php endif; ?>
<? if(get_field('dates', $post_object->ID)): ?>
<?php the_field('dates', $post_object->ID); ?>
<?php endif; ?>
</div>
</a>
<br><br>
<?php endforeach; ?>
<?php endif; ?>
这从后选择的每一个岗位,多数民众赞成返回文本自定义字段“标题”和“日期”在哪里这就是所谓的后场对象。
我希望帖子按发布日期的顺序返回。
任何想法?
答
<?php $post_objects = get_field('exhibitions');
$args = array (
'orderby'=>'date',
);
$the_query = new WP_Query($args);
if($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post(); ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<div style="display: inline-block">
<? if(get_field('title', $post_object->ID)): ?>
<em><?php the_field('title', $post_object->ID); ?></em><br>
<?php endif; ?>
<? if(get_field('dates', $post_object->ID)): ?>
<?php the_field('dates', $post_object->ID); ?>
<?php endif; ?>` </div>
</a>
<br><br>
endwhile;
wp_reset_postdata();
}
我还没有测试过,但它应该适用于你几乎没有适应!
答
好吧,我已经想通了!
与其说get_field
为post_objects
的,你把它作为一个变量只是为了获得有关职位的ID,然后用在了get_posts
的$args
的数组。这样,在运行循环之前,您可以访问get_posts
的所有阵列选项。
<?php
$ids = get_field('exhibitions', false, false);
$args = array(
'post__in' => $ids,
'orderby' => 'post_date',
);
$post_objects = get_posts($args);
if($post_objects): ?>
<?php foreach($post_objects as $post_object): ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<div style="display: inline-block">
<? if(get_field('title', $post_object->ID)): ?>
<em><?php the_field('title', $post_object->ID); ?></em><br>
<?php endif; ?>
<? if(get_field('dates', $post_object->ID)): ?>
<?php the_field('dates', $post_object->ID); ?>
<?php endif; ?>
</div>
</a>
<br><br>
<?php endforeach; ?>
<?php endif; ?>
感谢您的帮助!
发现我的回答感谢:http://support.advancedcustomfields.com/discussion/5846/adding-args-to-post_objects-get_field/p1
答
@迈克尔雷冯 - 你的答案的工作,但它涉及到从数据库得到相同的数据的两倍。相反,您可以对最初的ACF查询中返回的发布数据进行排序,而不是运行额外的查询。 (该POST_DATE返回一个字符串,因此您可以strcmp的话):
<?php
// get the posts from ACF
$custom_posts = get_field('your_posts_field');
// sort the posts by post date, but you can also sort on ID or whatever
usort($custom_posts, function($a, $b) {
return strcmp($b->post_date,$a->post_date);
});
// write them out
foreach ($custom_posts as $post) : setup_postdata($post); ?>
<article>
<h1><?php the_title();?></h1>
<?php the_excerpt(); ?>
</article>
<?php
endforeach;
wp_reset_query();
?>
帽尖到这个答案排序:https://stackoverflow.com/a/10159521
确定感谢看起来不错。唯一的一点是,它将所有可能的答案都返回给the_field('exhibitions');'而不是仅在'post_object'字段中选择的那些 – 2013-05-08 18:02:58