【发布时间】:2021-02-02 17:48:02
【问题描述】:
在我的 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 和回显号可以结合起来实现吗?
【问题讨论】:
-
你当然可以在 PHP 中运行 PHP。从
template-中删除连字符。get_template_part补充说。<?php get_template_part('partials/template', echo(rand(1,10)) ); ?> -
感谢您的回复。
<?php get_template_part('partials/template', echo(rand(1,10)) ); ?>抛出错误:“解析错误:语法错误,意外 'echo' (T_ECHO),期待 ')' in...” -
然后设置一个变量为随机数。
<?php $number = rand( 1, 10 ); get_template_part('partials/template', $number ); ?> -
是的!你明白了。
-
我会创建一个答案,因为这很有价值