已提交职位的年份一览表

时间:2019-06-11 作者:Michael Yakovis

我需要得到一份特定类别帖子的年份列表。如:2008、2009、2010、2012、2013(如果2011年没有帖子,则不包括在内)。

我尝试了这个查询,它成功了-我得到了我的年份列表:

$wpdb->get_results("SELECT YEAR(post_date) FROM {$wpdb->posts} 
WHERE post_status = \'publish\' GROUP BY YEAR(post_date) DESC");
然后我引入了类别ID,但什么都不起作用:

$wpdb->get_results("SELECT YEAR(post_date) FROM {$wpdb->posts} 
WHERE post_status = \'publish\' AND cat = \'4\' GROUP BY YEAR(post_date) DESC");
即使是简单的类别查询也不起作用:

$wpdb->get_results("SELECT YEAR(post_date) FROM {$wpdb->posts} WHERE 
cat = \'2\' GROUP BY YEAR(post_date) DESC");
具有此ID的类别肯定存在-这是类别列表中url的一部分:term.php?taxonomy=category&tag_ID=2&post_type=post

有一百多个帖子呢。

3 个回复
SO网友:nmr

中未存储职位和类别之间的关系posts 桌子您必须扩展查询以查找其他表。

按类别id:

SELECT YEAR(p.post_date) FROM {$wpdb->posts} p 
JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id 
JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id 
WHERE tt.term_id = 4 AND p.post_status = \'publish\' AND p.post_type = \'post\'
GROUP BY YEAR(p.post_date) DESC
或按类别slug:

SELECT YEAR(p.post_date) FROM {$wpdb->posts} p 
JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id 
JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id 
JOIN {$wpdb->terms} t ON t.term_id = tt.term_id  
WHERE t.slug = \'your_category_slug\' AND p.post_type = \'post\' AND p.post_status = \'publish\' 
GROUP BY YEAR(p.post_date) DESC

SO网友:HU ist Sebastian

这是因为类别关系不存储在wp\\u posts表中,而是存储在另一个名为wp\\u term\\u relationships的表中。

你必须做一些连接才能得到你想要的。这将为您提供今年发布帖子的一系列年份。

$years = $wpdb->get_results("SELECT DISTINCT YEAR($wpdb->posts.post_date) as year, COUNT($wpdb->posts.ID) as count FROM $wpdb->posts
    LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.taxonomy = \'category\' AND $wpdb->term_taxonomy.term_id = 4 AND $wpdb->posts.post_status = \'publish\' AND
$wpdb->posts.post_type = \'post\' 
GROUP BY YEAR($wpdb->posts.post_date) 
ORDER BY $wpdb->posts.post_date ASC");
快乐的编码!

SO网友:realloc

这些类别不存储在wp\\U POST中,而是存储在wp\\U terms-table中。请看一看here. 这里的查询应该更像这样:

SELECT YEAR(post_date) FROM wp_posts WHERE post_status = "publish" AND ID IN (
    SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (
        SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = "category" AND term_id = 4
    )
) GROUP BY YEAR(post_date) DESC;
您也可以使用WP_Query 如果您需要特定年份类别的职位列表:

$params = [ 
    \'cat\' => 4, 
    \'date_query\' => [
        [ \'year\' => 2016 ],
    ],
    \'posts_per_page\' => -1,
];
$query = new WP_Query( $params );