0

在我的 Wordpress 主题中,我有一个包含 10 个以数字后缀命名的文件的 partials 文件夹,我想get_template_part从这 10 个文件中选择 1 个随机文件。我认为最简单的方法是用数字差异并回显 1 到 10 之间的随机数——将添加到get_template_part.

目前我有以下内容,虽然我意识到你不能在 PHP 中运行 PHP。它们可以与这个逻辑结合起来吗?

<?php get_template_part('partials/template-', echo(rand(1,10)) ); ?>

部分文件夹中的文件名为:

template-1.php
template-2.php
template-3.php
[...]
template-10.php

可以get_template_part和回声数结合来实现这个吗?

4

1 回答 1

1

有几件事:

  1. 您需要从WP中删除-(连字符) 。get_template_part()
  2. 您可以通过变量传递随机数。
<?php
    // Assign the rand number to a variable 
    $number = rand( 1, 10 ); 
    // use the variable in the template part
    get_template_part('partials/template',  $number ); 
?>
于 2021-02-02T19:27:57.717 回答