Add ID to output only for first option

Joanna Mikalai asked
php functions
via

I am looking to add an extra ID to the output: <div id="NEWID" class="kalec"> if the shortcode is called with the value no=0 i.e. [photo no="0"]

I need to use an IF statement within my output but can’t figure out the correct syntax.

  function photo_shortcode($atts){
       extract(shortcode_atts(array(
          'no' => 1,
       ), $atts));

       $no     = ( $no       != ''     ) ? $no : 1;
       $images = get_field('fl_gallery');
       $image  = $images[$no];

    if ($image) {
       $credit = get_field('fl_credit', $image['id']);
       return '<div class="kalim"><img title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" src="' . $image['url'] . '" />' . (!empty($credit) ? '<div [INSERT IF STATEMENT] class="kalec"><div class="kalca">' . $image['caption'] . '</div><div class="kalcr">Credit:' . $credit . '</div></div>': '' ) . '</div>' ;
     }

    }


Answer
via

Instead of using an if check, use filter_var() so that any boolean-ish value can be passed in the shortcode attribute; e.g., yes, no, on, off, true, false, 0, 1.

$no = filter_var( $no, FILTER_VALIDATE_BOOLEAN );

Now, $no is either true or false (boolean).


Sorry, I see $no is actually a number. My mistake.

if ( $no === '0' ) {
    $no = 0;
} else {
    $no = (int) $no;
}

Uses strict comparison ===

Share This
Posted in: