WP_QUERY按年、月查找帖子

时间:2019-01-29 作者:Daler

我需要在分类法归档页面中按自定义帖子类型的年和月创建排序。

像这样:filter这里显示的是年份,如果该年存在post。如果当月存在帖子,则突出显示月份。

如何找出哪年哪月有帖子?如果每年每个月都有一个帖子,那么创建一个循环来检查,这将是“不好的”。有什么解决方案吗?

P、 S.cpt名称-document_base 和分类名称-document_base_categories 和字段中存储的日期docs_pubdate (自定义field suite插件)

1 个回复
最合适的回答,由SO网友:Daler 整理而成

通过创建自定义sql查询解决。

Request for years:

SELECT 
    count(*),
    $wpdb->posts.id as post_id_ts,
    YEAR(
        (SELECT 
            $wpdb->postmeta.meta_value 
        FROM 
            $wpdb->postmeta 
        WHERE 
            $wpdb->postmeta.post_id = post_id_ts 
        AND 
            $wpdb->postmeta.meta_key = \'docs_pubdate\')) 
    AS 
        years
FROM 
    $wpdb->posts
WHERE 
    $wpdb->posts.post_type = \'document_base\'
AND 
    $wpdb->posts.post_status = \'publish\'
GROUP BY 
    years
将返回如下结果:

Array ( 
    [0] => Array ( 
        [count(*)] => 1 
        [post_id_ts] => 1126 
        [years] => 2017 
    ) 
    [1] => Array ( 
        [count(*)] => 3 
        [post_id_ts] => 1121 
        [years] => 2019 
    ) 
) 

Request for months:

SELECT 
    count(*),
    $wpdb->posts.id as post_id_ts,
    MONTH(
        (SELECT 
            $wpdb->postmeta.meta_value 
        FROM 
            $wpdb->postmeta 
        WHERE 
            $wpdb->postmeta.post_id = post_id_ts 
        AND 
            $wpdb->postmeta.meta_key = \'docs_pubdate\')) 
    AS 
        months
FROM 
    $wpdb->posts
WHERE 
    $wpdb->posts.post_type = \'document_base\'
AND 
    $wpdb->posts.post_status = \'publish\'
GROUP BY 
    months
返回值为:

Array ( 
    [0] => Array ( 
        [count(*)] => 2 
        [post_id_ts] => 1121 
        [month] => 1 
    ) 
    [1] => Array ( 
        [count(*)] => 1 
        [post_id_ts] => 1122 
        [month] => 2 
    ) 
    [2] => Array ( 
        [count(*)] => 1 
        [post_id_ts] => 1126 
        [month] => 6 
    ) 
) 

相关推荐

Separate First Post Loop

我正在尝试使用<?php rewind_posts(); ?> 在我的主页模板上使用两个循环的功能。有人知道如何停止最新帖子后的第一个循环吗?这是我的代码:<?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1><a href=\"<?php the_permalink(); ?>\"><