php - 从 array_rand 函数的结果创建简码

标签 php arrays wordpress variables shortcode

我的 WordPress 网站的 functions.php 文件目前有这样的代码块:

function examplecode01() { 
$i = '<a href="/path/" class="exampleclass" id="example-code-01"><img class="example01imgclass" src="path/example01.jpg" alt="Example 01"/></a>';
return $i;
} 
add_shortcode('example-code-01', 'examplecode01');

其中有 5 个或更多,每个都有其各自的“示例代码 ##”变体,例如上述。简码行允许编辑指定简码并将特定横幅图像拉入博客文章(使用 add_shortcode 的第一个参数),如下所示:

[example-code-01]

我想做的是随机化它,这样编辑人员可以在任何地方使用相同的简码,并且它将是可用的随机横幅图像。

为了解决这个问题,我对上面的代码块进行了如下轻微修改:

function examplecode01() { 
echo '<a href="/path/" class="exampleclass" id="example-code-01"><img class="example01imgclass" src="path/example01.jpg" alt="Example 01"/></a>;
}  

(我删除了短代码行,因为它会导致下一节的输出出现问题——请耐心等待)。

好的,所以有几个修改过的代码块,每个都有自己的图像。在它们的最后,我有一个函数,如下所示:

$functions = array('examplecode01', 'examplecode02', 'examplecode03', 'examplecode04', 'examplecode05'); 
$functions[array_rand($functions)]();

当我将其放入一个空白的 PHP 文件(用于测试)并在线运行它时,它会从我列出的文件中随机输出一个横幅图像。万岁!成功......有点。

看,我现在需要的是编辑器通过短代码调用随机结果的方法。不过,我不是 100% 确定如何做到这一点。原始简码基本上是[“代码块中使用的id”,“函数名称”]

我考虑过将结果设置为一个变量,然后调用该变量,但我仍然不确定它如何“转换”(可以这么说)为短代码...

谁能帮我解决这个难题的最后一部分?提前致谢!

最佳答案

Creating a shortcode from the results of an array_rand function

我建议你换个角度看问题。与其根据 array_rand 调用的结果创建短代码,在我看来,您更想定义一个将显示随机横幅的短代码。

如果你想要一个返回随机横幅的短代码,像这样的东西可能会起作用:

function random_banner() {
    $banner_indexes = ['01', '02', '03', '04', '05'];
    $index = $banner_indexes[array_rand($banner_indexes)];

    return sprintf('<a href="/path/" class="exampleclass" id="example-code-%s"><img class="example%simgclass" src="path/example%s.jpg" alt="Example %s"/></a>', $index, $index, $index, $index);
}

add_shortcode('random-banner', 'random_banner');

关于php - 从 array_rand 函数的结果创建简码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878609/

相关文章:

java - 引用、浅复制和深复制

php - "Error establishing a database connection"Wordpress 和谷歌应用引擎

PHP 分页排序结果

PHP:返回每个数组元素的长度或停止

php - 使用 PHP 从数据库中检索数据

arrays - 如何查找一组特定值在数组中出现的次数?

javascript - WordPress 脚本不工作

php - WooCommerce - 添加 $order_total 到下订单按钮

php - 支付成功后,Woocommerce 中触发了什么钩子(Hook)

php - 将大型 json 字符串存储到数据库 + 哈希