【问题标题】:How to use same randomly generated value in header.php and footer.php in wordpress如何在 wordpress 的 header.php 和 footer.php 中使用相同的随机生成值
【发布时间】:2015-06-21 06:18:35
【问题描述】:

我想在 wordpress 的 header.php 和 footer.php 中使用相同的随机生成值。我试过这个函数来随机生成值:

function randValue() {
$randCheaters = substr(md5(microtime()),rand(0,26),5);
return $randCheaters;
}

在 header.php 中我使用了类似的东西

<header id="<? echo randValue(); ?>">

在footer.php中我使用了这个

<footer id="<? echo randValue(); ?>">

问题是它在页脚和页眉中生成不同的值,我怎样才能在两个地方获得相同的值。

【问题讨论】:

  • 只调用一次函数,存储返回值,回显两次
  • 嘿@Dagon你能给我一个例子我该怎么做。
  • 一个专业开发人员应该可以解决这个问题:)
  • @Dagon 非常好,非常正确 ;-)

标签: php wordpress random dynamically-generated


【解决方案1】:

与其每次通过函数调用生成随机数,不如在页面开始时一次执行,然后将其存储在一个变量中你稍后再打电话。

//No function, code runs automatically
$randCheaters = substr(md5(microtime()),rand(0,26),5);  //Variable $randCheaters now contains a random value

现在将 $randomCheaters 回显到两个 id 中,它们将是相同的

<header id="<? echo $randCheaters; ?>">
<footer id="<? echo $randCheaters; ?>">

【讨论】:

  • 还能用原来的功能
  • 但这是另一种方式,更简洁。做某事的方式总是不止一种:) @Dagon
  • 哦,你能给我你网站的链接吗?如果你不在本地主机上,我可以看看?
  • 我在本地主机@joe_young
  • 哦,它似乎对我有用。 header id 是否有效,即它只是缺少 id 的页脚?
【解决方案2】:

你必须在任何地方回显之前定义变量。从您的问题来看,随机代码似乎应该放在标题中。如您所知,标题部分可能紧跟在 html 标记之后。所以最好在 html 标记之前分配变量。

<?php $randCheaters = substr(md5(microtime()),rand(0,26),5); ?> <html>

我们不需要调用函数。现在在页眉和页脚下的id= 属性中回显。

如果您想在每个页面上都使用它,则将 rand 值分配给会话变量。

`$_SESSION['randCheaters']=$randCheaters;`

然后通过回显来使用这个会话变量。

从手机发帖。编辑选项是有限的。对不起,错误的对齐方式。

【讨论】:

  • 但在 wordpress 主题中 在 header.php 中,如果我使用 $randCheaters = substr(md5(microtime()),rand(0,26),5);在 header.php 中,它在 footer.php 中不起作用。所以它需要functions.php来生成值......
  • 您可以尝试解决方法。你有这个概念。
猜你喜欢
  • 1970-01-01
  • 2013-08-16
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多