0
votes

How I can add php code inside the function add_shortcode in functions.php

For Example:

<?php $images = get_field('img_novinki'); if( $images ) { ?>


<div id="carousel" class="flexslider">
    <ul class="slides gallery">
        <?php foreach( $images as $image ): ?>
            <li>
                <a href="<?php echo $image['url']; ?>"><img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
            </li>
        <?php endforeach; ?>
    </ul>
</div> <?php } ?>

Shortcode in functions PHP:

function my_novinki( $atts ) 
{
    return '';
}
add_shortcode( 'my_novinki', 'my_novinki');
2
I'm not sure I understand your question. The function add_shortcode is to create a shortcode, in this case it would be called using [my_novinki]. Then the code inside the function also named my_novinki will run. - Neil K
You need all your code in the my_novinki function? - Akshay Shah
Thank you so much for answer. I want to return ''; php code (look example) inside the shortcode. - Orkhan Hasanli
Yes, I try to add this php code (look example) to the page by using add_shortcode. - Orkhan Hasanli
shortcode are made to be used in the front end so they should not return PHP code. where you want to use it ? - Temani Afif

2 Answers

1
votes

See Codex: "..the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode."

You need to wrap your code in ob_start() and ob_get_clean():

add_shortcode( 'my_novinki', function my_novinki( $atts ) {
    ob_start();
    $images = get_field( 'img_novinki' );
    if( $images ) { ?>
        <div id='carousel' class='flexslider'>
            <ul class='slides gallery'> <?php
                foreach( $images as $image ) { ?>
                    <li>
                        <a href='<?php echo $image['url']; ?>'>
                            <img src='<?php echo $image['sizes']['thumbnail']; ?>' alt='<?php echo $image['alt']; ?>' />
                        </a>
                    </li> <?php
                } ?>
            </ul>
        </div> <?php
    }
    $out = ob_get_clean();
    return $out;
});
0
votes

From what I see you will need to do the following. In functions.php add:

function my_novinki( $atts ) 
{
   $images = get_field('img_novinki'); 

   if( $images ) {

    echo '<div id="carousel" class="flexslider">';
    echo '<ul class="slides gallery">';

      foreach( $images as $image ):
            echo '<li>';
            echo '<a href="'. $image["url"] .'"><img src="'.$image["sizes"]["thumbnail"] .'" alt="'. $image["alt"] .'" /></a>';
            echo '</li>';
      endforeach;

   echo '</ul>';
   echo '</div>'; 
  }

}

add_shortcode( 'my_novinki', 'my_novinki');

Then this can be called using [my_novinki] or if in a php template using <?php echo do_shortcode['my_novinki'];