【问题标题】:Random custom fields随机自定义字段
【发布时间】:2013-11-18 21:39:10
【问题描述】:

在我的主页上,我有 6 个块,每个块包括一些自定义字段。

我想随机显示这 6 个方块。

我的代码看起来像这样:

<div class="bloc">
<h2><?php the_field('titre1'); ?></h2>
<div class="content">
<p><?php the_field('description1'); ?></p>
</div>
<p class="more"><a href="<?php the_field('url1'); ?>">read more</a></p>
</div>

<div class="bloc">
<h2><?php the_field('titre2'); ?></h2>
<div class="content">
<p><?php the_field('description2'); ?></p>
</div>
<p class="more"><a href="<?php the_field('url2'); ?>">read more</a></p>
</div>

<div class="bloc">
<h2><?php the_field('titre3'); ?></h2>
<div class="content">
<p><?php the_field('description3'); ?></p>
</div>
<p class="more"><a href="<?php the_field('url3'); ?>">read more</a></p>
</div>

etc... (6 times)

你知道是否有办法随机化这个吗?

提前感谢您的帮助!

【问题讨论】:

  • 您的意思是希望 6 个中的 1 个出现(随机挑选),还是希望它们随机排序但每次都显示全部 6 个?
  • 第二个选项:我希望它们随机排序,每次显示 6 个,是的

标签: wordpress random custom-fields


【解决方案1】:

将每个块和push 获取到 php array 作为string。然后通过它们调用shuffle($array)foreach 来输出它们。

如果您需要更具体的说明,请告诉我。编辑:完整说明;

<?php 
// init array
$blocks = array();
// loop through 1 to 6
for($i=1;$i<=6;$i++) {
    // create a block of html
    // note I use $i here to get the correct fields
    // also note I've used get_field so its not echoed (as opposed to the_field)
    $block =    '<div class="bloc">
                    <h2>'.get_field('titre'.$i, 'option').'</h2>
                    <div class="content">
                        <p>'.get_field('description'.$i, 'option').'</p>
                    </div>
                    <p class="more"><a href="'.get_field('url'.$i, 'option').'">read more</a></p>
                </div>';
    // push this block of html into the array
    array_push($blocks, $block);
}
// shuffle the array of blocks randomly
shuffle($blocks);

// loop through them and echo out each html block
foreach ($blocks as $index => $block) {
    echo $block
} ?>

祝你好运!

编辑:抱歉,输入速度非常快,并且出现了一些错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2017-09-08
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多