WooCommerce:获取最新产品并(部分)随机排序
WooCommerce: Get newest products and sort them (partially) randomly
我想获取最后 20 个帖子(在我的例子中是 WooCommerce 产品)并以随机顺序显示其中的 10 个。
现在我得到这样的新帖子:
$args = array(
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 20,
);
我知道我可以像这样按随机顺序获取帖子:
'orderby' => 'rand',
'posts_per_page' => 10,
但这两者怎么可能结合呢?
w
有没有办法存储第一个循环中的帖子并在第二个循环中使用它们?
有几种方法可以做到这一点,这是其中一种
- wp_get_recent_posts( array $args = array(), string $output = ARRAY_A ) - 检索一些最近的帖子。
- shuffle ( array &$array ) : bool - 此函数打乱数组(随机排列元素的顺序)。它使用不适用于加密目的的伪随机数生成器。
- array_splice — 删除数组的一部分并将其替换为其他内容
$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 个帖子(在我的例子中是 WooCommerce 产品)并以随机顺序显示其中的 10 个。
现在我得到这样的新帖子:
$args = array(
'post_type' => 'product',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 20,
);
我知道我可以像这样按随机顺序获取帖子:
'orderby' => 'rand',
'posts_per_page' => 10,
但这两者怎么可能结合呢? w 有没有办法存储第一个循环中的帖子并在第二个循环中使用它们?
有几种方法可以做到这一点,这是其中一种
- wp_get_recent_posts( array $args = array(), string $output = ARRAY_A ) - 检索一些最近的帖子。
- shuffle ( array &$array ) : bool - 此函数打乱数组(随机排列元素的顺序)。它使用不适用于加密目的的伪随机数生成器。
- array_splice — 删除数组的一部分并将其替换为其他内容
$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();