WP按年份查询帖子 [英] WP Query post by year in accordion

查看:55
本文介绍了WP按年份查询帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get the testimonials (custom post type) in following order.

我可以使用WP_Query类轻松检索帖子,但如上面的屏幕快照所示,正在努力创建手风琴.

I can easily retrieve posts using WP_Query class but struggling to create an accordion as shown in the screenshot above.

推荐答案

尝试使用自定义选择查询并遍历每个帖子都带有post_type的推荐信.

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

Then loop through result and set WP_Query() class date_query param to an array of the years obtained by the custom select query result.

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;

     }
}

这篇关于WP按年份查询帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆