Query multiple custom taxonomy terms in Wordpress

2020-02-04 21:22发布

I created a custom taxonomy named 'technologies' but cannot query multiple terms like I can with categories or tags.

These querys DO work:

query_posts('tag=goldfish,airplanes');

query_posts('technologies=php');

However, neither of the following work correctly:

query_posts('technologies=php,sql');

query_posts('technologies=php&technologies=sql');

My objective: Show all posts with a technology of 'php' and all posts with a technology of 'sql'

Any ideas? Is this even possible? Thanks!

9条回答
smile是对你的礼貌
2楼-- · 2020-02-04 22:18

Does this work? query_posts('tag=bread+baking+recipe')

From: http://codex.wordpress.org/Template_Tags/query_posts

查看更多
姐就是有狂的资本
3楼-- · 2020-02-04 22:20

it should be like this:

        global $wp_query;
        query_posts(
                array_merge(
                    array('taxonomy' => 'technologies', 'term' => array('sql', 'php')),
                    $wp_query->query
                )
            );

that works for custom post_types, at least.

查看更多
狗以群分
4楼-- · 2020-02-04 22:20
 //equivalent to get_posts
 function brand_get_posts($args=array()){
global $wpdb;
$sql = "SELECT p.* ";
$sql.= " FROM $wpdb->posts p";
$sql.= " LEFT JOIN $wpdb->term_relationships term_r ON(p.ID = term_r.object_id)";
$sql.= " LEFT JOIN $wpdb->term_taxonomy term_t ON(term_r.term_taxonomy_id = term_t.term_taxonomy_id)";
$sql.= " LEFT JOIN $wpdb->terms terms ON(term_t.term_id = terms.term_id)";
$sql.= " WHERE 1=1 ";
if(!empty($args['post_type'])){
    $sql.= " AND p.post_type = '".$args['post_type']."'";
}   
$sql.= " AND p.post_status = 'publish'";

if(!empty($args['taxonomy'])){
    $sql.= " AND term_t.taxonomy = '".$args['taxonomy']."'";
}   
if(!empty($args['terms'])&&is_array($args['terms'])){
    $sql.= " AND terms.slug IN ('".implode(",",$args['terms'])."')";
}
$sql.= " ORDER BY p.post_date DESC";
if(!empty($args['posts_per_page'])){
    $sql.=" LIMIT ".$args['posts_per_page'];
}
if(!empty($args['offset'])){
    $sql.=" OFFSET ".$args['offset'];
}
//echo '<h1>'.$sql.'</h1>';
return $wpdb->get_results($sql);
 }
查看更多
登录 后发表回答