简体   繁体   中英

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

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. Offset that second query each time it runs by dividing the iteration counter by 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();
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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