簡體   English   中英

執行 1 個查詢以從每個類別中獲取 3 個帖子

[英]Execute 1 query to get 3 posts from each category

我想從每個類別中獲取 3 個帖子(如果存在),並且只執行一個查詢來獲取所有帖子。

例如,如果我有 3 個類別,那么我想從所有類別中獲得總共 9 個帖子。

下面是我如何使用循環來執行多個查詢:

$query  = new WP_Query;

foreach ( $cats as $cat ) :
    $query->query( array(
        'cat'                 => $cat->term_id,
        'posts_per_page'      => 3,
        'no_found_rows'       => true,
        'ignore_sticky_posts' => true,
    ));

我試過這個:

    $args = array(
            'posts_per_page' => 3,
            'order'          => 'desc',
            'post_type'      => 'post',
            'cat'  => array(19,20,2,3),
            'ignore_sticky_posts' => true
        ); 
   $args['orderby'] = 'post_views';
   $posts = get_posts( $args );

如果每個類別或所有現有類別都存在,我無法弄清楚如何獲得 3 個帖子。

結果我只收到了第一類的 3 個帖子

嘗試以下

$args = array(
'cat'      => array(1,2,3),
'order'    => 'ASC',
'showposts' => 3
    );
query_posts($args);
<?php

    $cat_args = array (
        'orderby' => 'name',
        'order' => 'ASC',
    );

    $threecategories = get_categories( $cat_args ); 

    foreach ( $threecategories as $threecategory ) {

        echo '<a href="' . esc_url( get_category_link( $threecategory->term_id ) ) . '">' . $threecategory->name . '</a>';

        $post_args = array(
            'posts_per_page' => 3,
            'cat' => $threecategory->cat_ID
        );

        $threeposts = query_posts( $post_args );

        while(have_posts()) : the_post();

            echo '<a href="' . esc_url( get_the_permalink() ) . '">' . get_the_title(). '</a>';

        endwhile; 
    }
    wp_query_reset();

可能這會幫助你

暫無
暫無

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

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