【问题标题】:Randomize array content in PHP via Wordpress posts通过 Wordpress 帖子在 PHP 中随机化数组内容
【发布时间】:2014-06-17 13:36:11
【问题描述】:

你们知道如何限制每页的帖子并在 wordpress 中随机发布帖子吗?

我在后端有一个关系字段,我在其中添加和删除我创建的要在网站中显示的项目。此内容通过下面的 WP_Query 打印出来:

<?php
  $args = array (
    'post_type'      => 'home_banners'

  $fullbanner = new WP_Query ( $args );
?>

这里是 PHP:

<?php if ( have_posts() ) : while ( $fullbanner->have_posts() ) : $fullbanner->the_post(); ?>

#####Get the relationship field
<?php $banners = get_field('home_banner_01_selection'); ?>
#####Check if the relationship field has contents
<?php if( $banners ): ?>
  #####Start foreach
  <?php foreach( $banners as $banner ): ?>
    <a href="<?php the_field('home_link', $banner->ID ); ?>"><?php the_field( 'home_headline', $banner->ID ); ?></a>
  <?php endforeach; ?>
<?php endif; ?>

我在这个关系字段中添加了三个内容。我只想每页显示一个内容,并在刷新页面时将其随机化。目前它正在显示页面中的所有三个内容。

我注意到 var $banners 的行为类似于 array。如果我添加echo count($banners);,它将显示3。此外,如果我添加shuffle($banners);,它将在它们之间打乱内容。

谢谢你帮助我。

【问题讨论】:

    标签: php arrays wordpress random posts


    【解决方案1】:

    您可以打乱数组 $banners,然后在数组 wit 中回显帖子

    <?php
        $banners = get_field('home_banner_01_selection');
        if($banners) {
            shuffle($banners);
            ?>
                <a href="<?php the_field('home_link', $banners[0]->ID ); ?>"><?php the_field( 'home_headline', $banners[0]->ID ); ?></a>
            <?php
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多