PHP 中的字符串比较 - 不断返回错误的值


String compare in PHP - Keep returning wrong value

在WordPress中,我使用了一个插件,该插件记录了一个元键_featured并添加"是"或"否"的值。如果它有特色,我想添加 css,但是无论结果如何,它都会添加div。

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

并非所有这些都是为了结束,其中一些只是为了测试日志的结果。

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

这是添加div 的代码。无论值是"是"还是"否",它都会添加它。

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

最后一部分只是为了检查我自己的价值是多少。

不确定我哪里出错了。

您的 HTML 没有包装在 PHP 中,因此不受条件语句的影响

改变

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

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

php if.. 的语法。尾部为:

if (condition):
   ...
endif;

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

所以你需要改变

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

to(注意 if 语句中 == 之后的额外 :

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