問題描述

雖然我已經能夠使這項工作適用於正常的 WP 類別,但我無法使其適用於自定義分類法。

我想迴圈使用每個習慣分類法 (我的案例中的類別),併為每個分類法生成一些帖子。

輸出的一個例子是:

Category 1

post from category one
post from category one

read more category one


Category 2

post from category two
post from category two

read more category two

當然,它會透過任何可用的分類法來重複定製帖子型別。

最佳解決方案

我以為我會提供另一個答案,因為上面的一個有點駭客,我還新增了另一個層,獲得一個 post_type 的所有分類。

$post_type = 'post';

// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type ) );

foreach( $taxonomies as $taxonomy ) : 

    // Gets every "category" (term) in this taxonomy to get the respective posts
    $terms = get_terms( $taxonomy );

    foreach( $terms as $term ) : 

        $posts = new WP_Query( "taxonomy=$taxonomy&term=$term->slug&posts_per_page=2" );

        if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post();
            //Do you general query loop here  
        endwhile; endif;

    endforeach;

endforeach;

建議將發現的每個帖子新增到 $post__not_in 陣列中,以便將其傳遞給 WP_Query,以防止重複的帖子透過。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。