简体   繁体   中英

Add php code inside the function add_shortcode in functions.php Wordpress

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');

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;
});

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'];

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