使用三元运算符的 echo 中的 if 语句

if statment within an echo using ternary operators

我有以下回显语句:

echo '<li><a href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';

我想在参数 = 1

时将 class "disabled" 添加到 link

这是我正在尝试使用三元运算符

    $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>';

但是这会产生语法错误。我该如何正确写出来?

只需在函数调用后立即使用一个变量,class 为 "disabled" 或无(“”):

$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>";

如果你只需要class,你甚至可以立即检查函数调用:

$class = (get_post_meta( $the_query->post->ID, 'deposit_paid', true ))?"disabled":"";

需要解决三个问题:

  • 三元运算符需要 ... 3 个参数(惊喜!),所以在第二个之后,您需要在 else 中添加 : 和您想要的字符串案例.

  • 在构建字符串时应用点运算符之前,应将整个三元表达式(而不是条件)放在方括号中。

  • 你需要比较,而不是赋值(==而不是=

这样就可以了:

$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>';