代码之家  ›  专栏  ›  技术社区  ›  Cray

WooCommerce:获取最新产品并随机(部分)排序

  •  1
  • Cray  · 技术社区  · 4 年前

    我想得到最后20个帖子(在我的例子中是WooCommerce产品),并以随机顺序显示其中的10个。

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

    我知道我可以像这样随机地得到这些帖子:

    'orderby'                       => 'rand',
    'posts_per_page'                => 10,
    

    但这两者怎么可能结合起来呢? 有没有一种方法可以存储第一个循环中的帖子并在第二个循环中使用它们?

    1 回复  |  直到 4 年前
        1
  •  1
  •   7uc1f3r    4 年前

    有几种方法可以做到这一点,这是其中之一

    $recent_posts = wp_get_recent_posts( array(
        'numberposts' => 20, // Number of recent posts
        'post_status' => 'publish', // Show only the published posts
        'post_type'   => 'product'
    ));
    
    // array_splice ( array, offset, length )
    $sub = array_splice( $recent_posts, 10, 10 );
    
    // Random
    shuffle( $sub );
    
    array_splice( $recent_posts, 10, 0, $sub );
    
    // Loop
    foreach( $recent_posts as $post ) {
        echo $post['ID'] . '<br>';
        //echo '<pre>', print_r( $post, 1), '</pre>';
    }
    
    wp_reset_query();