简体   繁体   English

显示来自 WP Query 的帖子和每 4 个帖子,显示 4 个带有分类的帖子

[英]Display posts from WP Query and every 4 posts, display 4 posts with taxonomy

I need help creating a query that displays posts from custom post type and every 4 posts, display 4 posts that contains a taxonomy of the same post我需要帮助创建一个查询,该查询显示来自自定义帖子类型的帖子,每 4 个帖子显示 4 个包含同一帖子分类的帖子

Should I do two different queries?我应该做两个不同的查询吗? Normal taxonomy:正常分类:

 $args = array( 'post_type' => 'news', 'posts_per_page' => -1, ); $news = new WP_Query($args);

Taxonomy query:分类查询:

 $args = array( 'post_type' => 'news', 'offset' => 4, 'tax_query' => array( array( 'taxonomy' => 'news-category', 'field' => 'slug', 'terms' => 'the-community', ), ), ); $community = new WP_Query($args);

I don't know how to iterate to get the query I want我不知道如何迭代以获得我想要的查询

You'll need to use iteration in your loop.您需要在循环中使用迭代。 Then inside that loop run another query to loop the second group of posts each time the iteration counter is evenly divisible by 4 using modulo operator.然后在该循​​环内运行另一个查询以循环第二组帖子,每次迭代计数器使用模运算符被 4 整除。 Offset that second query each time it runs by dividing the iteration counter by 4.每次运行时通过将迭代计数器除以 4 来偏移第二个查询。

I haven't test the following code to be functional, but conceptually it should be valid.我还没有测试以下代码是否可以正常工作,但从概念上讲它应该是有效的。

[Edited] [已编辑]

$args = array(
    'post_type' => 'news',
    'posts_per_page' => -1,
);

$news = new WP_Query($args);

// Get Loopy
if ( $news->have_posts() ) {
    $i = 0; // Set iteration to 0
    while ( $news->have_posts() ) {
        
        $news->the_post();
        $i++; // Increment iteration counter

        // News post output
        echo the_title();

        // Check if iteration counter is evenly divisible by 4 using the modulo operator (%).
        if ( $i % 4 == 0 ) {
            
            $posts_per_page = 4;

            // Get your offset.
            $offset = $i - $posts_per_page;

            $args = array(
                'post_type' => 'news',
                'posts_per_page' => $posts_per_page,
                'offset' => $offset,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'news-category',
                        'field'    => 'slug',
                        'terms'    => 'the-community',
                    ),
                ),
            );

            $community = new WP_Query($args);

            while ( $community->have_posts() ) {
                
                $community->the_post();
                // Community post output
                echo the_title();
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM