我已经获得以下代码,该代码将显示定义类别中的4个随机帖子。但是,这有点过于随机,我需要它来显示最近的4个,然后在每次刷新页面时特别随机化它们。
否则我最终会在主页上找到可以追溯到2年前的文章。
<div class="article-block-v1">
<?php
//get terms (category ids 11,2,33,34), then display one post in each term
$taxonomy = 'category';// e.g. post_tag, category
$param_type = 'category__in'; // e.g. tag__in, category__in
$term_args=array(
'include' => '1459',
);
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
foreach( $terms as $term ) {
$args=array(
"$param_type" => array($term->term_id),
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 4,
'orderby' => 'rand',
);
$my_query = null;
$my_query = new WP_Query($args);
$i = 1;
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php if ($i == 1): ?>
<div class="article-block-v1">
<div class="category-label-large category-news-analysis">
<a href="<?php the_permalink(); ?>"><p><?php echo $term->name; ?></p></a>
</div>
<div class="view2 third-effect">
<?php the_post_thumbnail(); ?>
<div class="mask">
<a href="<?php the_permalink() ?>" class="info" ><i class="fa fa-search"></i></a>
</div>
</div>
<ul class="homepagewhitebg">
<li><h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5></li>
</ul>
</div>
<?php else: ?>
<li><a href="<?php the_permalink(); ?>"><p><?php the_title(); ?></p></a></li>
<?php endif; ?>
<?php
$i++;
endwhile;
echo '</ul>';
}
}
}
wp_reset_query(); // Restore global post data stomped by the_post().
?>
演示1(最近4次) - 没有随机排序的常规
文章#1001
文章#1002
文章#1003
第1004条
演示2(最近4次 - 但随后在这4位上随机排序)
文章#1003
文章#1001
文章#1004
文章#1002
更新 我现在也尝试这个,但是它没有考虑我已经定义的类别,也没有在所显示的4个中随机化:
<div class="article-block-v1">
<?php
$number = "4";
$posts = "SELECT * from $wpdb->posts WHERE post_type='post' ORDER BY post_date DESC LIMIT $number";
$postX = array();
$postresult = mysql_query($posts) or die(mysql_error());
while ($row = mysql_fetch_array($postresult)) {
$postX[] = $row[0];
}
$ids = shuffle($postX);
$ids = implode(',', $postX);
echo $ids;
?>
<?php
$args = array(
'posts_per_page'=> $number,
'post__in' => explode(',', $ids),
'include' => '1451',
'orderby' => 'rand'
);
query_posts($args);
?>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
答案 0 :(得分:1)
您可以使用shuffle()。在改组之前,你想要获得最近的4篇帖子(按顺序)。很简单,您可以执行以下操作:
// Get the 4 most recent posts
$args = array( 'numberposts' => 4 );
$recent_posts = wp_get_recent_posts( $args );
// Shuffle them
shuffle($recent_posts)
foreach( $recent_posts as $recent ){
// Do something with the $recent post
}
您可能需要将额外的$args
传递给该函数,以满足您的特定约束。