Patrick Cauley
Patrick Cauley

Reputation: 971

String compare in PHP - Keep returning wrong value

In WordPress I'm using a plug in that logs a meta key _featured and adds a value of yes or no. I want to add css if it is featured, however it is adding the div no matter what the result.

            <?php if ( get_post_meta( get_the_ID(), '_featured', true ) ) : ?>
                <?php $feat = get_post_meta( get_the_ID(), '_featured', true ); ?>
                            <?php if( strcasecmp($feat, yes) == 0)?>
                                <a href=""><div class="featured_reject">Featured Rejection</div></a>

                            <?php endif; ?>
                            <h1><?php echo get_post_meta( get_the_ID(), '_featured', true ) ?></h1>
                <?php endif; ?>

Not all of this is intended for the end, some of it is just to test the results of the log.

            <?php if ( get_post_meta( get_the_ID(), '_featured', true ) ) : ?>

This checks if there is a value. Works fine.

<?php $feat = get_post_meta( get_the_ID(), '_featured', true ); ?>

Logging it as a variable

<?php if( strcasecmp($feat, 'yes') == 0)?>
                                    <a href=""><div class="featured_reject">Featured Rejection</div></a>

                                <?php endif; ?>

This is the code to add the div. It adds it regardless of whether the value is yes or no.

<h1><?php echo get_post_meta( get_the_ID(), '_featured', true ) ?></h1>
                    <?php endif; ?>

This last portion is simply to check what the value is for myself.

I'm not sure where I am going wrong.

Upvotes: 0

Views: 1343

Answers (2)

Marc
Marc

Reputation: 11

The syntax of the php if..endif is:

if (condition):
   ...
endif;

(per: http://php.net/manual/en/control-structures.alternative-syntax.php )

So you need to change

<?php if( strcasecmp($feat, yes) == 0)?>
    <a href=""><div class="featured_reject">Featured Rejection</div></a>
<?php endif; ?>

to (note the extra : after ==) in the if statement:

<?php if( strcasecmp($feat, yes) == 0):?>
    <a href=""><div class="featured_reject">Featured Rejection</div></a>
<?php endif; ?>

Upvotes: 1

Lloyd Banks
Lloyd Banks

Reputation: 36648

Your HTML isn't wrapped in PHP and thus isn't affected by the conditional statement

Change

<?php if( strcasecmp($feat, 'yes') == 0)?>
                                    <a href=""><div class="featured_reject">Featured Rejection</div></a>

                                <?php endif; ?>

to

<?php 
  if(strcasecmp($feat, 'yes') == 0){
       echo "<a href = ''><div class = 'featured_reject'>Featured Rejection</div></a>"
  }
?>

Upvotes: 2

Related Questions