【问题标题】:WooCommerce: Get newest products and sort them (partially) randomlyWooCommerce:获取最新产品并(部分)随机排序
【发布时间】:2020-09-06 09:55:23
【问题描述】:

我想获取最后 20 个帖子(在我的情况下为 WooCommerce 产品)并以随机顺序显示其中的 10 个。

现在我收到这样的新帖子:

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

我知道我可以像这样以随机顺序获取帖子:

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

但是如何将这两者结合起来呢? w 有没有办法存储第一个循环中的帖子并在第二个循环中使用它们?

【问题讨论】:

    标签: php wordpress random woocommerce product


    【解决方案1】:

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

    $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();
    

    【讨论】:

    • 谢谢!抱歉,我忘了说我只想以随机顺序显示 20 个帖子中的 10 个。这就是我考虑第二个循环的原因。
    • 答案已更新,对于您的其他问题,您可以使用array_splice
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多