php 条件if和else语句逻辑工作,但它是最佳的吗?

z0qdvdin  于 5个月前  发布在  PHP
关注(0)|答案(2)|浏览(46)

我还是PHP的新手,写了这个if-else语句,它工作,但我没有足够的信心把它放在我的博客上:

  • 如果是主页,显示logo.png
  • 如果不是主页&如果有缩略图,显示缩略图。
  • 如果它不是主页&没有缩略图,显示徽标。

我的代码是正确的和最佳的吗?

<?php if(is_home() || is_front_page()){ ?>
      <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
      <?php } else if (!is_home() || !is_front_page()){ ?>
      <?php if( !empty(get_the_post_thumbnail()) ) { ?>
        <meta property="og:image" content="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'medium_large'); ?>" />
        <?php } else { ?>
        <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
      <?php } ?>
    <?php } ?>

字符串

9rygscc1

9rygscc11#

你的代码会很好地工作,作为一个很好的实践,我们必须记住优化这个词,如果我们在这里认为同样的话,如果不需要,我们可以在else里面写同样的东西。

<?php if (is_home() || is_front_page()) { ?>
        <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
    <?php } else { ?>
        <?php if (!empty(get_the_post_thumbnail())) { ?>
            <meta property="og:image" content="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'medium_large'); ?>" />
        <?php } else { ?>
            <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
        <?php } ?>
    <?php } ?>

字符串

wmvff8tz

wmvff8tz2#

由于您只需要在两个不同的值之间切换,因此可以在一个if/else中完成。
我还将该值添加到PHP变量中,而不是在if/else的. Imo中复制HTML代码,这有助于可读性和可维护性。

<?php
$isHomeOrFront = is_home() || is_front_page();

if (!$isHomeOrFront && !empty(get_the_post_thumbnail())) {
    $ogImage = get_the_post_thumbnail_url(get_the_ID(), 'medium_large');
} else {
    $ogImage = get_template_directory_uri() . '/images/logo.png';
}
?>

<meta property="og:image" content="<?= $ogImage ?>">

字符串
另一种选择是使用三进制操作而不是if/else。这取决于个人喜好。

$ogImage = (!$isHomeOrFront && !empty(get_the_post_thumbnail()))
    ? get_the_post_thumbnail_url(get_the_ID(), 'medium_large')
    : get_template_directory_uri() . '/images/logo.png';

相关问题