[英]How can I use a “variable” in an if/or statement in PHP to generate a statement conditionally?
I have zero experience with PHP. 我对PHP零经验。 I run a wordpress site, and am trying to make one simple modification to the code.
我运行了一个wordpress网站,并试图对代码进行一个简单的修改。 This is what I have:
这就是我所拥有的:
<?php
if(<?php the_author() ?> == "Joe Man")
{
<?php the_author() ?>
}
?>
I believe all variables start with a $, so what I have above in my if statement is not a variable. 我相信所有变量都以$开头,因此我上面的if语句中的内容不是变量。 What do I do?
我该怎么办? I also tried creating a variable, as below:
我也尝试创建一个变量,如下所示:
<?php
$author = <?php the_author() ?>
if($author == "Joe Man")
{
<?php the_author() ?>
}
?>
Neither of the above worked. 以上两种都不起作用。 So my question is how can I get that if statement to evaluate?
所以我的问题是,如何获取if语句进行评估? What I need is if the_author is "Joe Man", for the string "Joe Man" to display on my page.
我需要的是the_author是“ Joe Man”,字符串“ Joe Man”要显示在我的页面上。
This is the error I get btw: 这是我得到的错误:
Parse error: syntax error, unexpected '<' 解析错误:语法错误,意外的“ <”
Thanks! 谢谢!
You may not nest <?php ?>
tags. 您不能嵌套
<?php ?>
标记。 The correct code would be: 正确的代码是:
<?php
$author = get_the_author();
if ($author == "Joe Man") {
echo $author;
}
?>
Actually, the variable could be skipped altogether, shortening the code to: 实际上,可以完全跳过该变量,从而将代码缩短为:
<?php
if (get_the_author() == "Joe Man") {
the_author();
}
?>
Note the echo to print out the author. 注意回显以打印出作者。
Looks like you're using wordpress, so beyond your PHP-in-PHP error, your code wouldn't work anyways, as both the_author()
calls will simply OUTPUT the data, instead of returning it for comparison. 看起来您使用的是wordpress,因此除了您的PHP-in-PHP错误之外,您的代码也无法正常工作,因为两个
the_author()
调用都只会输出数据,而不是返回数据进行比较。 You'd want: 您想要:
$author = get_the_author();
if ($author == "Joe Man") {
echo $author;
}
instead. 代替。 As a general rule, any function in Wordpress which does output has a
get_...()
variant which returns instead of outputting. 通常,Wordpress中任何可输出的函数都具有
get_...()
变体,该变体返回而不是输出。
If the author is "Joe Man", output the author: 如果作者是“ Joe Man”,请输出作者:
<?php
$author = the_author();
if($author == "Joe Man") {
echo $author;
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.