简体   繁体   中英

How I can use php if statment in wordpress shortcode?

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM