Answer a question

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?

Answers

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.

  • Source @ https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters

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 );
Logo

WooCommerce社区为您提供最前沿的新闻资讯和知识内容

更多推荐