在 WordPress 2.8 中查询多个自定义分类术语?

发布于 07-27 22:55 字数 420 浏览 14 评论 0原文

我创建了一个名为“技术”的自定义分类法,但无法像使用类别或标签那样查询多个术语。

这些查询确实有效:

query_posts('tag=goldfish,airplanes');

query_posts('technologies=php');

但是,以下两项都无法正常工作:

query_posts('technologies=php,sql');

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

我的目标:显示使用“php”技术的所有帖子以及使用“sql”技术的所有帖子'

有任何想法吗? 这可能吗? 谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

薄荷港2024-08-03 22:55:30

显然,query_posts 在这种特定情况下无法提供帮助。 (希望它将被添加到 Wordpress 的未来版本中!)解决方案是使用自定义选择查询,如下所示:

SELECT * 
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)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->posts.post_type = 'post' 
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'technologies'
AND $wpdb->terms.slug = 'php' OR $wpdb->terms.slug = 'css'
ORDER BY $wpdb->posts.post_date DESC

更多信息可以在 Wordpress Codex 中找到:
http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

Apparently query_posts cannot help in this specific situation. (Hopefully it will be added in future versions of Wordpress!) The solution is to use a custom select query like the following:

SELECT * 
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)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->posts.post_type = 'post' 
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'technologies'
AND $wpdb->terms.slug = 'php' OR $wpdb->terms.slug = 'css'
ORDER BY $wpdb->posts.post_date DESC

More information can be found at the Wordpress Codex:
http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

何以畏孤独2024-08-03 22:55:30

这是一个有点延迟的回复,但它目前在 Google 上是第一个“wordpress 相关帖子的多个术语”,所以我想贡献我的发现。

自从这个问题发布以来,Wordpress 已经被更改为允许这种类型的查询。 这将为您提供与分配给对象的任何自定义分类术语相关的帖子列表:

$post_cats = wp_get_object_terms(get_the_ID(), 'video_category', array('fields' => 'ids'));

$args=array(
    "tax_query" => array(
        array(
            "taxonomy" => "video_category",
            "field" => "id",
            "terms" => $post_cats
        )
    ),
    'post__not_in' => array(get_the_ID()),
    'post_type' => 'video',
    'posts_per_page' => 8,
    'caller_get_posts' => 1
);

$related_by_cats = new WP_Query($args);

这是我对 SO 的第一个贡献,我希望它符合标准。

This is a bit of a delayed reply, but it's first on Google at the moment for "wordpress related posts by multiple terms" so thought I'd contribute my findings.

Since this question was posted Wordpress has been changed to allow for this type of query. This will give you a list of posts related by any of the custom taxonomy terms assigned to an object:

$post_cats = wp_get_object_terms(get_the_ID(), 'video_category', array('fields' => 'ids'));

$args=array(
    "tax_query" => array(
        array(
            "taxonomy" => "video_category",
            "field" => "id",
            "terms" => $post_cats
        )
    ),
    'post__not_in' => array(get_the_ID()),
    'post_type' => 'video',
    'posts_per_page' => 8,
    'caller_get_posts' => 1
);

$related_by_cats = new WP_Query($args);

This is my first contribution to SO, I hope it's up to standards.

入怼2024-08-03 22:55:30

这有效吗? query_posts('tag=bread+baking+recipe')

来自: http://codex.wordpress.org/ Template_Tags/query_posts

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

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

蓝天白云2024-08-03 22:55:30

好的,这就是我的破解方法。 这有点hacky,但是很有效。 最大的缺点是需要重新添加任何其他查询变量,因为当调用多个术语时,失败会删除所有查询变量。

另外,我没有针对跨多个分类法的查询进行测试。 这只适用于特定的分类法。 使用风险自负。

function multi_tax_terms($where) {
    global $wp_query;
    if ( strpos($wp_query->query_vars['term'], ',') !== false && strpos($where, "AND 0") !== false ) {
        // it's failing because taxonomies can't handle multiple terms
        //first, get the terms
        $term_arr = explode(",", $wp_query->query_vars['term']);
        foreach($term_arr as $term_item) {
            $terms[] = get_terms($wp_query->query_vars['taxonomy'], array('slug' => $term_item));
        }

        //next, get the id of posts with that term in that tax
        foreach ( $terms as $term ) {
            $term_ids[] = $term[0]->term_id;
        }

        $post_ids = get_objects_in_term($term_ids, $wp_query->query_vars['taxonomy']);

        if ( !is_wp_error($post_ids) && count($post_ids) ) {
            // build the new query
            $new_where = " AND wp_posts.ID IN (" . implode(', ', $post_ids) . ") ";
            // re-add any other query vars via concatenation on the $new_where string below here

            // now, sub out the bad where with the good
            $where = str_replace("AND 0", $new_where, $where);
        } else {
            // give up
        }
    }
    return $where;
}

add_filter("posts_where", "multi_tax_terms");

OK, so here is my crack at this. It's a little hacky, but it works. The big downside is that any other query variables need to be re-added, as when multiple terms are invoked, the fail strips out all of the query vars.

Also, I did not test this against querying across multiple taxonomies. This only works within a specific taxonomy. Use at your own risk.

function multi_tax_terms($where) {
    global $wp_query;
    if ( strpos($wp_query->query_vars['term'], ',') !== false && strpos($where, "AND 0") !== false ) {
        // it's failing because taxonomies can't handle multiple terms
        //first, get the terms
        $term_arr = explode(",", $wp_query->query_vars['term']);
        foreach($term_arr as $term_item) {
            $terms[] = get_terms($wp_query->query_vars['taxonomy'], array('slug' => $term_item));
        }

        //next, get the id of posts with that term in that tax
        foreach ( $terms as $term ) {
            $term_ids[] = $term[0]->term_id;
        }

        $post_ids = get_objects_in_term($term_ids, $wp_query->query_vars['taxonomy']);

        if ( !is_wp_error($post_ids) && count($post_ids) ) {
            // build the new query
            $new_where = " AND wp_posts.ID IN (" . implode(', ', $post_ids) . ") ";
            // re-add any other query vars via concatenation on the $new_where string below here

            // now, sub out the bad where with the good
            $where = str_replace("AND 0", $new_where, $where);
        } else {
            // give up
        }
    }
    return $where;
}

add_filter("posts_where", "multi_tax_terms");
指尖凝香2024-08-03 22:55:30

在 WP 中实现自定义分类法之后,没有内置函数可以随意使用它们,而且文档几乎不存在,这在某种程度上是愚蠢的。 我一直在寻找解决方案,这个查询解决了它(并让我很高兴)。 谢谢。

不过,遗憾的是我太笨了(OOP 盲),无法将其变成一个函数,所以我不再重复它。
我得到: **致命错误**:在非对象上调用成员函数 get_results()

我想我不知道如何调用 $wpdb在一个函数内。

It's somehow silly that after implementing custom taxonomies in WP there are no built-in functions to use them at will, and the documentation is close to non-existent. I was looking for a solution, this query solves it (and made my day). Thanks.

Still, sadly I'm too dumb (OOP blind) to make it into a function so I don't repeat it all over.
I get: **Fatal error**: Call to a member function get_results() on a non-object

I guess I don't know how to call $wpdb from within a function.

半寸时光2024-08-03 22:55:30

它应该是这样的:

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

至少适用于自定义 post_types。

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.

鲜血染红嫁衣2024-08-03 22:55:30

嘿嘿,我也遇到过同样的问题。 如果您没有很多多个值,那么您可以通过以下方式执行此操作,而不是编写原始 SQL 查询:

$loop = new WP_Query(array('technologies' => 'php','technologies' => 'sql')); 

然后您可以循环访问此处创建的 wp_query 对象。
虽然这是一篇非常旧的帖子,但我确信您已经解决了这个问题。 :)

Hey, I also faced the same problem once. If you don't have many multiple values, then you can do it in the following way, rather than writing a raw SQL query:

$loop = new WP_Query(array('technologies' => 'php','technologies' => 'sql')); 

Then you can loop through the wp_query object created here.
Though this is a very old post and am sure you have already solved the problem. :)

猫九2024-08-03 22:55:30
 //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);
 }
 //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);
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文