【问题标题】:WP Query post by year in accordionWP Query post by year in 手风琴
【发布时间】:2019-02-28 18:08:41
【问题描述】:

我正在尝试按以下顺序获取推荐(自定义帖子类型)。

我可以使用 WP_Query 类轻松检索帖子,但难以创建手风琴,如上面的屏幕截图所示。

【问题讨论】:

  • 你能发布你的代码吗?

标签: php wordpress accordion custom-post-type


【解决方案1】:

Try using a custom select query and looping through each post with a post_type of testimonial.

然后循环遍历结果并将WP_Query() classdate_query参数设置为自定义选择查询结果获得的年份数组。

global $wpdb;

$posts = $wpdb->posts;

//Get all unique years as "years" from posts where post type is equal to testimonials

$sql = "SELECT DISTINCT(YEAR(`post_date`)) as years FROM $posts WHERE post_type = 'testimonials' ORDER BY years DESC"; //Get all post year list by DESC


//Loop through all results and use date_query param https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters


$result = $wpdb->get_results($sql);

foreach($result as $rs) {
    echo '<h2>'.$rs->years.'</h2>';
    $args = array(
        'post_type' => 'testimonials',
        'post_per_page'=> -1,
        'post_status' => 'publish',
        'orderby'   => 'date',
        'order' => 'DESC',
        'date_query' => array(array(
            'year'=> $rs->years,
        ),),

    );

     $loop = new WP_Query($args);

     if($loop->have_posts()) {

        while($loop->have_posts()) : $loop->the_post();

            echo '<a href="'.get_permalink().'">'.get_the_date().'</a>';
        endwhile;

     }
}

【讨论】:

    【解决方案2】:

    @user3325126 很棒的代码,谢谢 :) 只需将 'post_per_page'=> -1, 替换为 'posts_per_page'=> -1, (缺少一个) 应该是

    'posts_per_page'=&gt; -1,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      相关资源
      最近更新 更多