简体   繁体   中英

WordPress: Combine two loops with different amount of posts

I want to show a random selection of 4 new products in WooCommerce.

For that I'm using a first loop to get the 20 newest products. Like this:

$args= array(
    'post_type'         => 'product',
    'posts_per_page'    => 20,
    'orderby'           => 'date',
);

Now I've a second loop to reduce the products to 4 in a random order:

$args_new = array(
    'posts_per_page'    => 4,
    'orderby'           => 'rand',
);

In the end I merge the two loops:

$final_args = array_merge( $args, $args_new );

But that doesn't work. Is there any other way to achieve it?

General knowledge


The post_type argument accept String or Array .

Argument Description
post_type ( String / Array ) – use post types. Retrieves posts by post types, default value is post . If tax_query is set for a query, the default value becomes any .

Merging queries


In crude terms we want to combine 2 posts queries, retrieve each posts ID, push them to a new array and open a new query.

Keep in mind that if you want your 4 posts to be random (as you stated in the comments) they might be some duplicates of the last 20 from the first query. Don't forget to offset the second query.

<?php

// First query
$args_1 = get_posts( array(
    'post_type' => 'dogs',
    'post_status' => 'publish',
    'post_count' => 20,
) );

// Second query
$args_2 = get_posts( array(
    'post_type' => 'dogs',
    'post_status' => 'publish',
    'post_count' => 4,
    'offset' => 20,
    'orderby' => RAND,
) );

// Merge queries
$posts = array_merge( $args_1, $args_2 );

// Push posts IDs to new array
$identifiers = array();

foreach ( $posts as $post ) {

  array_push( $identifiers, $post->ID );

};

// Third query
$query = new WP_Query( array(
  'post_status' => 'publish',
  'post_count' => 24,
  'post_in' => array_unique( $identifiers ),
) );

var_dump( $query );

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