admin管理员组文章数量:1434972
I'm working with a tag plugin. Is there a WordPress way to get_posts or query all posts that have no tags?
EDIT
I had already queried the WP Codex, search Stackexchange and Google for a related question at the time of the question.
I found several results for helping finding tags, but not the NOT IN
operator in a tax_query
. I didn't have any code to share yet as I didn't have the information I needed to build the query $args
.
I'm working with a tag plugin. Is there a WordPress way to get_posts or query all posts that have no tags?
EDIT
I had already queried the WP Codex, search Stackexchange and Google for a related question at the time of the question.
I found several results for helping finding tags, but not the NOT IN
operator in a tax_query
. I didn't have any code to share yet as I didn't have the information I needed to build the query $args
.
3 Answers
Reset to default 8A WP_Query
where 'tax_query'
has all tag terms and operator 'NOT IN':
$tags = get_terms('post_tag', array('fields'=>'ids') );
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => $tags,
'operator' => 'NOT IN'
)
)
);
$untagged = new WP_Query( $args );
Not exactly answers the question, but might be a better solution than the above when dealing with bigger databases
// Get all posts IDs - Query took 0.0030 seconds
$all_posts_ids_query = $wpdb->prepare( "SELECT $wpdb->posts.ID FROM $wpdb->posts WHERE $wpdb->posts.post_type = '%s' GROUP BY $wpdb->posts.ID", 'your-post-type' );
$all_posts_ids = $wpdb->get_col( $all_posts_ids_query );
// Get all posts IDs that has tags - Query took 0.0300 seconds
$all_posts_ids_with_tags_query = $wpdb->prepare( "SELECT $wpdb->posts.ID FROM $wpdb->posts
INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE 1=1 AND ( $wpdb->term_taxonomy.taxonomy = '%s' )
AND $wpdb->posts.post_type = '%s' GROUP BY $wpdb->posts.ID", 'your-taxonomy-name', 'your-post-type' );
$all_posts_ids_with_tags = $wpdb->get_col( $all_posts_ids_with_tags_query );
// Diff IDs arrays to get posts without tags
$all_posts_ids_without_tags = array_diff( $all_posts_ids, $all_posts_ids_with_tags );
DB size this was tested on (quite small but may give some representation), posts: ~3.000, terms: ~1.000, term relationships: ~6.000
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => 'null',
'operator' => 'NOT IN'
)));
$untagged = new WP_Query( $args );?>
本文标签: wp queryGet all posts without tags
版权声明:本文标题:wp query - Get all posts without tags 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745628473a2667120.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论