【问题标题】:Querying posts from same categories / tags查询来自相同类别/标签的帖子
【发布时间】:2014-01-03 16:16:58
【问题描述】:

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

            $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;

它正在工作,但有没有办法在一个查询中做到这一点?

【问题讨论】:

  • 有一种方法可以在一个查询中完成所有操作。以良好的格式向我们提供表格布局,让我们知道您到底想要什么,我们将引导您朝着正确的方向前进。

标签: wordpress post optimization tags categories


【解决方案1】:

这个问题已经在 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;

【讨论】:

  • 谢谢。它工作正常,但我上面的示例包含类别和标签之间的“或”关系,而不是“和”。这就像按类别或标签选择帖子。可以放进去吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
相关资源
最近更新 更多