Get all posts without tags

时间:2013-09-20 作者:Poe

我正在使用一个标签插件。有没有WordPress方法可以获取\\u帖子或查询所有没有标签的帖子?

EDIT

在提问时,我已经向WP Codex、search Stackexchange和Google查询了一个相关问题。

我发现了一些有助于查找标记的结果,但不是NOT IN a中的运算符tax_query. 我还没有任何代码可以共享,因为我没有构建查询所需的信息$args.

3 个回复
最合适的回答,由SO网友:gmazzap 整理而成

A.WP_Query 哪里\'tax_query\' 具有所有标记项和运算符“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 );

SO网友:meloniq

这并不能完全回答这个问题,但在处理更大的数据库时,这可能是一个更好的解决方案

// 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 );
测试的数据库大小(非常小,但可能有一些代表性),帖子:~ 3000条,术语:~ 1000条,术语关系:~ 6000条

SO网友:A\'dii Sunlay
<?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 );?>
结束

相关推荐

H1 tags for header image?

在里面heading.php 叶主题的代码如下: <?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) { ?> <a href=\"<?php echo esc_url( home_url( \'/\' ) ); ?>\" title=\"<?php echo esc_attr( get_bloginfo( \'name\', \