普通网友 2015-03-03 20:03
浏览 49
已采纳

如何在wordpress短代码中使用php if语句?

I will try to make a WordPress plugin. My all code is ok but I can't understand how I use if else statement in custom post shortcode.

global $post;
        $accordion_icon = get_post_meta($idd, 'accordion_icon', true);

        $list .= '
                <div class="collapse-card">
                <div class="title">
                    <i class="fa '.$accordion_icon.' fa-2x fa-fw"></i>
                    <strong>'.get_the_title().'</strong>
                </div>
                <div class="body">
                    <p>'.get_the_content().'</p>
                </div>
                </div>
                ';

It's my present code. Hear have a icon option in title div .I will want to when I put any custom icon code then show the custom icon and when I don't put any custom icon code then show a common icon. I can understand here need to use if else statement but I don't understand how I use if else statement in my code.

$list .= '
                <div class="collapse-card">
                <div class="title">
                '<?php if($accordion_icon) : ?>'
                    <i class="fa '.$accordion_icon.' fa-2x fa-fw"></i>
                '<?php else : ?>'
                    <i class="fa fa-question-circle fa-2x fa-fw"></i>
                '<?php endif; ?>'

                    <strong>'.get_the_title().'</strong>
                </div>
                <div class="body">
                    <p>'.get_the_content().'</p>
                </div>
                </div>
                ';  

I used like that but it's not working.Show error .

So now how I can use if else statement ?

  • 写回答

1条回答 默认 最新

  • donjd86266 2015-03-03 20:16
    关注

    You can do it either like this (short way):

    $list .= '<div class="collapse-card">
              <div class="title">';
    if($accordion_icon)
        $list .= '<i class="fa '.$accordion_icon.' fa-2x fa-fw"></i>">';
    else
        $list .= '<i class="fa fa-question-circle fa-2x fa-fw"></i>';
    

    Or like this (long way):

    $list .= '<div class="collapse-card">
              <div class="title">';
    if($accordion_icon){
        $list .= '<i class="fa '.$accordion_icon.' fa-2x fa-fw"></i>">';
    }else{
        $list .= '<i class="fa fa-question-circle fa-2x fa-fw"></i>';
    }
    

    Note: You can only use the short way for 1 line. If your body statement exceeds 1 line you require the curly braces.

    You can also used something called the coditional operator, but I don't think that's what you're looking for, for now.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘