【问题标题】:WordPress: Display Posts by Year Set in Advanced Custom FieldsWordPress:在高级自定义字段中按年份显示帖子
【发布时间】:2015-02-12 16:36:45
【问题描述】:

我正在尝试根据在“高级自定义字段”日期选择器中输入的内容(不是发布年份)按年份组织帖子。我已经能够非常接近我正在寻找的使用年份检查器:http://alex.leonard.ie/2009/08/27/wordpress-grouping-posts-by-monthyear/

我想要完成的是:

2015

  • 往届展览
  • 往届展览

2014

  • 往届展览
  • 往届展览

2013

  • 往届展览
  • 往届展览

唯一的问题是,虽然我可以成功打印年份,但每年只列出一个展览。

    <?php if (have_posts()) : ?>
    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $today = date('Ymd');

    $past_args = array(
        'paged' => $paged,
        'posts_per_page' => -1,
        'post_type' => 'exhibitions',
        'meta_query' => array (
            array (
                'key' => 'end_date',
                'value' => $today,
                'compare' => '<',
                'type' => 'DATE'
            )
        ),
        'orderby' => 'meta_value_num',
        'order' => 'DESC'                   
    );
    query_posts( $past_args );
    ?> 


    <!-- PAST EXHIBITIONS -->
    <?php while (have_posts()) : the_post(); ?>

    <?php   
        $date = get_field('end_date');
        $past_year = DateTime::createFromFormat('Ymd', $date);
        $year = $past_year->format('Y');

        if ($year !== $today) { ?>
            <article class="year-<?php echo $year; ?> child-page four columns">
            <h2><?php echo $year; ?></h2>
            <ul>
                <li>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                </li>
            </ul>
            </article>
        <?php }

        $today = $year; ?>

    <?php endwhile; ?>
    <?php endif; ?>

我错过了什么/做错了什么?

【问题讨论】:

  • 您是否收到任何 PHP 错误?
  • 我打开调试并意识到 $year_check 实际上并没有在任何地方定义(并且在我发布的文章中没有解释),所以我使用了 $today 变量代替它,但我运行进入同一个问题。
  • 这可能无助于解决您的问题,但您应该在&lt;?php endwhile; ?&gt; 之后添加&lt;?php wp_reset_postdata(); ?&gt;
  • 如果你做了一些,你应该定义$year_check或更新你的代码。

标签: wordpress advanced-custom-fields


【解决方案1】:

答案其实很简单。从 if 语句中取出 post 内容等。

您只想打印一年,但显示所有帖子。

<?php while (have_posts()) : the_post(); ?>

<?php   
    $date = get_field('end_date');
    $past_year = DateTime::createFromFormat('Ymd', $date);
    $year = $past_year->format('Y');

    if ($year !== $today) { ?>
        <h2><?php echo $year; ?></h2>
    <?php } ?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php $today = $year; ?>

<?php endwhile; ?>

您必须做一些尝试才能让您的 ul 和 article 元素在您想要的位置打开和关闭,但是通过仅使用 if 语句来回显年份,您的循环的其余部分应该正常进行。

【讨论】:

  • 谢谢!这真的很简单!我想我只需要离开它一会儿,用一双新的眼睛看着它。
猜你喜欢
  • 2016-06-25
  • 2014-07-31
  • 2020-07-08
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
相关资源
最近更新 更多