Wordpress类别/分类法查询

时间:2017-11-17 13:20:21

标签: sql wordpress

我需要从我的类别6中获取我在wordpress中的所有帖子而且只有这一个,我不想查询帖子有2个类别,如帖子" X"有类别6和9.
我坚持我的查询的这一部分,并想知道我是否应该使用NOT IN,如果这会使我的查询更慢?

 SELECT p.*, t.term_id
        FROM wp_posts p
        LEFT JOIN wp_term_relationships rel ON rel.object_id = p.ID
        LEFT JOIN wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
        LEFT JOIN wp_terms t ON t.term_id = tax.term_id
        WHERE t.term_id = 6
        ORDER BY p.post_date DESC Limit 10;

1 个答案:

答案 0 :(得分:0)

我认为您需要获取所有条款并删除所有不等于您想要的terms_id的条款ID。

检查一下。我添加了一些注释来解释这个过程

function get_posts_from_single_cat($cat_id) {
    // Get all the categories
    $cats = get_terms(array('taxonomy'=>'category'));
    $cats_ids = array();
    foreach($cats as $cat) {
        // Check if the category is NOT equal to the category that we want
        // Then we add it into array
        if($cat->term_id !== $cat_id) {
            $cats_ids[] = $cat->term_id;
        }
    }

    // then we create WP_Query with the category that we want and checking that its not in the other categories
    $args = array(
        'post_type' => 'post',
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => array( $cat_id )
            ),
            array (
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => $cats_ids,
                'operator' => 'NOT IN'
            )
        ),
    );
    $query = new WP_Query( $args );
    // then do something with the posts...
}