【问题标题】:Echo random number inside Wordpress' get_template_part在 Wordpress 的 get_template_part 中回显随机数
【发布时间】: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 ); ?>
  • 是的!你明白了。
  • 我会创建一个答案,因为这很有价值

标签: php wordpress random echo


【解决方案1】:

有几件事:

  1. 您需要从 get_template_part() 中删除 -(连字符),因为 WP 添加了这一点。
  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 ); 
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多