我想将我的自定义帖子类型分为几年。
我应该看起来像
2019年职位1职位2职位3
2018年职位1职位2
2015年第1期
年鉴1。。n
以下示例:Order and group posts by acf by month and year 我的代码是这样设置的。
<?php get_header(); ?>
<?php /* Template Name: Konzerte */
// Überschrift-Element mit Headline, Bild, Schwung und Text; 800px hoch
require(\'inc/stage.php\'); ?>
<?php
// get posts
$posts = get_posts(array(
\'post_type\' => array(\'concertreport\', \'concertannouncement\'),
\'posts_per_page\' => -1,
\'meta_key\' => \'concertdate\',
\'orderby\' => \'meta_value\',
\'order\' => \'DESC\'
));
?>
<?php
$group_posts = array();
if( $posts ) {
foreach( $posts as $post ) {
$date = get_field(\'concertdate\', $post->ID, false);
$date = new DateTime($date);
$year = $date->format(\'Y\');
$group_posts[$year][] = array($post, $date);
}
}
foreach ($group_posts as $yearKey => $years) { ?>
<h2><?php echo $yearKey; ?></h2>
<?php foreach ($years as $postKey => $posts) { ?>
<?php echo $posts[1]->format(\'d-m-Y\');
echo \' / \';
echo $posts[0]->post_title;
echo \'<br>\';
// Instead of "echo $posts[0]->post_title;" I want to display the ACF-(Sub-)fields like teaser-text, image, etc.
}
}
?>
<?php get_footer(); ?>
结果非常好:
正如您在我的评论中所看到的,我想在那里显示ACF字段。自定义图像、自定义摘要文本等。我不知道为什么,如果我从ACF那里复制代码,例如标题而不是注释:
<div class="col-md-7 bg-wso-white">
<?php the_title( \'<h3 class="font-weight-bold text-left text-wso-black text-uppercase pb-1"><a href="\' . get_permalink() . \'" title="\' . the_title_attribute( \'echo=0\' ) . \'" rel="bookmark">\', \'</a></h3>\' ); ?>
</div>
结果,不太好;-):
它只会重复显示所有帖子最早日期的文本。我的acf子字段根本不显示。有人能帮我吗?
最合适的回答,由SO网友:Louis S 整理而成
无法使用ACF或函数(如\\u title())的原因是,只能从循环内部访问它们(请参见此处https://codex.wordpress.org/The_Loop).
没有必要有多个循环,所以我将它们合并到一个循环中,以显示您需要的任何帖子数据。在这个循环中,它检查当前职位的年份是否等于前一个职位的年份,然后再显示它。
<?php /* Template Name: Konzerte */
// Überschrift-Element mit Headline, Bild, Schwung und Text; 800px hoch
require(\'inc/stage.php\');
global $post;
// get posts
$posts = get_posts(array(
\'post_type\' => array(\'concertreport\', \'concertannouncement\'),
\'posts_per_page\' => -1,
\'meta_key\' => \'concertdate\',
\'orderby\' => \'meta_value\',
\'order\' => \'DESC\'
));
$group_posts = array();
if ($posts) {
$previous_year = \'\';
foreach ($posts as $post) {
$date = get_field(\'concertdate\', $post->ID, false);
$date = new DateTime($date);
$current_year = $date->format(\'Y\');
// If $previous_year is empty, display $current_year
if ($previous_year == \'\') {
echo \'<h2>\' . $current_year . \'</h2>\';
}
// Else if $previous_year is not equal to $current_year, display $current_year
else if ($previous_year !== $current_year) {
echo \'<h2>\' . $current_year . \'</h2>\';
}
$previous_year = $date->format(\'Y\');
echo $date->format(\'d-m-Y\');
echo \' / \';
echo get_the_title();
echo \'<br>\';
}
}
?>
<?php get_footer(); ?>