Sam Skirrow
Sam Skirrow

Reputation: 3697

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?

Upvotes: 2

Views: 178

Answers (2)

Jan
Jan

Reputation: 43169

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

Upvotes: 1

trincot
trincot

Reputation: 350781

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

Upvotes: 3

Related Questions