簡體   English   中英

查詢相同類別/標簽的帖子

[英]Querying posts from same categories / tags

我想找到所有來自相同類別和相同標簽的帖子,例如插件中的特定帖子。 因此,實際上我通過查詢標簽和類別來單獨執行此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM