$wpdb按月份、帖子类型和分类术语选择查询

时间:2016-12-20 作者:Tyler

我正在尝试创建一个柱状图,在选定的帖子类型和分类法中以月为单位列出帖子数量。

我有这个查询,它的工作原理与它应该的完全一样,但它不包括所选的分类术语。

$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不是很了解,如果能学会怎么做就好了,我已经在谷歌上搜索了几个小时,没有任何进展。

1 个回复
最合适的回答,由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 值作为自定义分类名称,如categorypost_tag. 在这里terms_tax.taxonomy 值不是强制的,但它会使结果更精确。

希望这有帮助。

相关推荐

$wpdb->get_row返回什么?

由于插件中的调试和错误查找,我有一个简短的问题。$wpdb->;如果没有结果,返回get\\u row()?文件说明:(array|object|null|void) Database query result in format specified by $output or null on failure. 但当查看源代码时,它似乎返回了;null“;。。。如果您能快速提供帮助,我将不胜感激,我一直认为它会返回一个空数组,但我可能弄错了!