我正在尝试创建一个柱状图,在选定的帖子类型和分类法中以月为单位列出帖子数量。
我有这个查询,它的工作原理与它应该的完全一样,但它不包括所选的分类术语。
$post_type_query = " AND post_type = \'" . $selected_post_type . "\'";
$posts_per_month = $wpdb->get_results(
"SELECT DATE_FORMAT(post_date, \'%Y-%m\') as month, count(ID) as count
FROM $wpdb->posts wposts
WHERE post_status = \'publish\'" . $post_type_query .
"GROUP BY month",
OBJECT_K
);
它输出这是完美的
Array
(
[2016-11] => stdClass Object
(
[month] => 2016-11
[count] => 1
)
[2016-12] => stdClass Object
(
[month] => 2016-12
[count] => 10
)
)
然而,我似乎无法让它按选定的分类术语过滤倒计时。这就是我尝试过的
$posts_per_month = $wpdb->get_results(
"SELECT DATE_FORMAT(post_date, \'%Y-%m\') as month, count(ID) as count
FROM $wpdb->posts wposts
LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id
LEFT JOIN $wpdb->term_relationships ON (wposts.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 post_status = \'publish\'" . $post_type_query .
"AND term_taxonomy = \'business\'" .
"GROUP BY month",
OBJECT_K
);
这不会输出任何内容,因为我猜我的sql已关闭。我对sql不是很了解,如果能学会怎么做就好了,我已经在谷歌上搜索了几个小时,没有任何进展。
最合适的回答,由SO网友:CodeMascot 整理而成
您尚未加入wp_terms
或$wpdb->terms
WordPress存储术语名称的表。下面是更新后的代码-
$post_type_query = " AND post_type = \'" . $selected_post_type . "\'";
$posts_per_month = $wpdb->get_results(
"SELECT *, DATE_FORMAT(post_date, \'%Y-%m\') AS month, COUNT(ID) AS count
FROM {$wpdb->posts} AS wposts
LEFT JOIN {$wpdb->postmeta} AS wpostmeta ON (wposts.ID = wpostmeta.post_id)
LEFT JOIN {$wpdb->term_relationships} AS tax_rel ON (wposts.ID = tax_rel.object_id)
LEFT JOIN {$wpdb->term_taxonomy} AS term_tax ON (tax_rel.term_taxonomy_id = term_tax.term_taxonomy_id)
LEFT JOIN {$wpdb->terms} AS terms ON (terms.term_id = term_tax.term_id)
WHERE post_status = \'publish\'" . $post_type_query .
"AND terms.name = \'business\'
AND term_tax.taxonomy = \'your-custom-taxnomy-name\'",
OBJECT_K
);
在上述代码中输入
terms.name
作为术语名称的值,以及
terms_tax.taxonomy
值作为自定义分类名称,如
category
或
post_tag
. 在这里
terms_tax.taxonomy
值不是强制的,但它会使结果更精确。
希望这有帮助。