doulangpeng3933 2013-12-10 00:11
浏览 26
已采纳

如果输入为空,如何使用PHP显示其他内容?

My WordPress options panel has a section where the user can paste their logo's URL to show up in the header. If the input is blank, I want the Blog's title to show up instead on my header. The ID of the input is "nl_logo", so I added an if statement in my header.

<?php if ("nl_logo") { ?>
    <img src="<?php echo get_option('nl_logo'); ?>">
<?php } else { ?>
    <h1><a href="'get_site_url()' ?>"><?php bloginfo('name'); ?></a></h1>
<?php } ?>

The first part of the if statement works. However, anything below else doesn't work when I have no URL saved in my input. So, if the input is empty, how do I display something else with PHP? Or is there a different and better way to do this? For example, creating a function and calling the results to display with a simple line of PHP?

  • 写回答

6条回答 默认 最新

  • dpjjmo3079 2013-12-10 00:20
    关注

    Try this... also try to understand it.

    Keeping with the established coding style:

    <?php $nlLogo = get_option('nl_logo'); ?>
    <?php if (empty($nlLogo)) { ?>
        <h1><a href="<?php echo(get_site_url()); ?>"><?php echo(bloginfo('name')); ?></a></h1>
    <?php } else { ?>
        <img src="<?php echo($nlLogo); ?>">
    <?php } ?>
    

    That should atleast be valid PHP now. I don't know if the functions you are using are correct, but if they are this should work.

    Here is a cleaner way to do it...

    <?php
        $nlLogo = get_option('nl_logo');
        if (empty($nlLogo)) {
            echo('<h1><a href="'.get_site_url().'">'.bloginfo('name').'</a></h1>');            
        } else {
            echo('<img src="'.$nlLogo.'">');
        }
    ?>
    

    Option three because I'm feeling "teachy" using a ternary. Probably a little long for this to be the best choice, but it is another option.

    <?php
        $nlLogo = get_option('nl_logo');
        echo(empty($nlLogo) ? '<h1><a href="'.get_site_url().'">'.bloginfo('name').'</a></h1>' : '<img src="'.$nlLogo.'">');
    ?>
    

    Note I switched the if / else because I'm using empty and it just feels cleaner to do it this way instead of using !empty()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建