[英]if statment within an echo using ternary operators
I have the following echo statement: 我有以下回显语句:
echo '<li><a href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';
I want to add the class "disabled" to the link when a parameter = 1 我想在参数= 1时将“禁用”类添加到链接中
Here is what I am trying using ternary operators 这是我尝试使用三元运算符的内容
$is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
echo '<li><a '.( $is_deposit_paid = 1) ? "disabled" .' href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';
however this produces a syntax error. 但是,这会产生语法错误。 How do I write this out correctly? 如何正确写出?
There are three issues to solve: 有三个问题要解决:
ternary operator requires ... 3 arguments (surprise!), so after the second, you need to add the :
and the string you want in the else
case. 三元运算符需要... 3个参数(惊奇!),因此在第二个参数之后,需要在else
情况下添加:
和所需的字符串。
the whole ternary expression should be put in brackets (not the condition) before you apply the dot operator to it in building your string. 在将点运算符应用于构建字符串之前,应将整个三元表达式放在方括号(而不是条件)中。
You need to compare, not assign ( ==
instead of =
) 您需要比较而不是分配( ==
而不是=
)
So this would do it: 所以这样做:
$is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
echo '<li><a '.( $is_deposit_paid == 1 ? "disabled" : "") .
' href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID,
site_url( '/pay-deposit/' ) )) .
'">Pay deposit</a></li>';
Just use a variable right after your function call with the class being "disabled" or nothing (""): 只需在函数调用后立即使用一个变量,而该类为“禁用”或什么都没有(“”):
$is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
$class = ($is_deposit_paid)?"disabled":"";
echo "<li><a $class href='". esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) ."'>Pay deposit</a></li>";
If you only need the class, you could even check the function call immediately: 如果只需要类,甚至可以立即检查函数调用:
$class = (get_post_meta( $the_query->post->ID, 'deposit_paid', true ))?"disabled":"";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.