简体   繁体   English

按计数获取自定义分类术语列表,其中包含自定义 post_type 帖子

[英]Get the list of custom taxonomy terms by count which have custom post_type posts

In my WP v5.9.3, I have custom post type "song" and a shared custom taxonomy "genre".在我的 WP v5.9.3 中,我有自定义帖子类型“歌曲”和共享的自定义分类法“流派”。

On the Songs archive page, I want to list all the terms of "genre" taxonomy with count, which have posts in "song" post type.在歌曲存档页面上,我想列出所有带有计数的“流派”分类法术语,这些术语在“歌曲”帖子类型中有帖子。

With get_terms I was able to get all the terms from "genre", but cannot filter terms which has "song" posts.使用get_terms我能够从“流派”中获取所有术语,但无法过滤具有“歌曲”帖子的术语。

Though I am not expert at SQL Query, I have tried below but not able to get the list:虽然我不是 SQL 查询的专家,但我在下面尝试过但无法获得列表:

    $SQLquery = "SELECT wp_terms.* COUNT(*)from wp_terms
                 SELECT wp_posts.ID FROM wp_posts
                 INNER JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
                 INNER JOIN wp_term_relationships ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
                 INNER JOIN wp_posts ON wp_posts.ID = wp_term_relationships.object_id
                 WHERE 1=1 
                 AND wp_posts.post_type IN ('song')
                 AND wp_posts.post_status = 'publish'
                 AND wp_term_taxonomy.taxonomy = 'genre'
                 GROUP BY wp_terms.term_id
                 ORDER BY wp_terms.term_id DESC";

    $SQLqueryResult = $wpdb->get_results($SQLquery, ARRAY_A);

    $SQL_term_ids = wp_list_pluck($SQLqueryResult, 'term_id');

How can I make the above SQL query work to get the terms list or is there any simple / built-in WordPress function?如何使上述 SQL 查询工作以获取术语列表,或者是否有任何简单/内置的 WordPress function? Thank you.谢谢你。

Update 1更新 1

Issue was with multiple SELECT in SQLquery , when removed SELECT wp_posts.ID FROM wp_posts the code worked as required.问题出在SQLquery中的多个SELECT中,当删除SELECT wp_posts.ID FROM wp_posts时,代码按要求工作。

There is an issue concerning the begin of your query.您的查询开头存在问题。 You can't use two selects like this.你不能像这样使用两个选择。 When you want to select multiple columns, you need to use comma, meaning "select table1.column1, table2.column1...from yourselection."当你想要select多列时,你需要使用逗号,意思是“select table1.column1, table2.column1...from yourselection”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM