随机抽取X条最新的文字媒体帖子


Randomise X most recent wordpress posts

我得到了以下代码,它将显示定义类别中的4个随机帖子。然而,这有点太随机了,我需要它来显示最近的4个,然后在每次刷新页面时将它们随机化。

否则,我的主页上就会出现可以追溯到两年多前的文章。

<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个最近的-但按随机顺序排列)
文章#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; ?>

您可以使用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