查询相同类别/标签的帖子

时间:2014-01-03 16:16:59

标签: wordpress post optimization tags categories

我想查找来自相同类别和相同标签的所有帖子,例如插件中的特定帖子。所以我实际上是通过查询标签和类别来单独完成的:

            $taxonomy_arr = wp_get_post_tags( $this->post->ID, array( "fields" => "ids" ) );
            add_filter( 'posts_where', array( $this, 'additional_filter' ) );

            foreach ( $taxonomy_arr as $tag_id ) {  
                $posts_arr = get_posts( array(
                    'posts_per_page'   => $this->max_results,
                    'tag_id'    => (int) $tag_id,
                    'post_type' => array( $this->included_post_types ),
                    'orderby' => 'rand',
                    'suppress_filters' => false
                 ) );

                 // add to categories selection
                if ( is_array( $posts_arr ) ) {
                    foreach ( $posts_arr as $post_obj ) {
                        if ( is_object( $post_obj ) ) {
                            $local_taxonomy_selection[] = (int) $post_obj->ID;
                        }
                    }
                }
            }   

            // get post categories
            $category_array = get_the_category( $this->post->ID );
            foreach ( $category_array as $category ) {  
                $posts_arr = get_posts( array(
                    'posts_per_page'   => $this->max_results*2,
                    'category'    => $category->cat_ID,
                    'post_type'   => array( $this->included_post_types ),
                    'orderby' => 'rand',
                    'suppress_filters' => false
                 ));

                 // add to categories selection
                if ( is_array( $posts_arr ) ) {
                    foreach ( $posts_arr as $post_obj ) {
                        if ( is_object( $post_obj ) ) {
                            $local_category_selection[] = (int) $post_obj->ID;
                        }
                    }
                }
            }
// combine post id's arrays
$all_posts = $local_taxonomy_selection + $local_category_selection;

它有效,但有一种方法可以在一个查询中完成吗?

1 个答案:

答案 0 :(得分:0)

这个问题已经在wordpress.stackexchange上得到答案。所以在这里复制相同的代码。

https://wordpress.stackexchange.com/questions/4201/how-to-query-posts-by-category-and-tag

global $wp_query;
        $args = array(
        'category__and' => 'category', 
        'tag__in' => 'post_tag', //must use tag id for this field
        'posts_per_page' => -1

$posts = get_posts($args);
        foreach ($posts as $post) :
  //do stuff 
     endforeach;