简体   繁体   中英

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

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.

  • 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":"";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM