H
H
hypero2021-12-07 14:32:12
WordPress
hypero, 2021-12-07 14:32:12

Can't create a shortcode?

Hello.
I can't create a shortcode, I'm probably doing it wrong.

function true_misha_func( $atts ){ ?>
    <div class="slider">
        <div class="slider-init">
            <?php foreach(getSlider() as $slider_post): setup_postdata($slider_post); ?>
            <div class="slider-item">
                <div class="container">
                    <div class="slider-item-inner">
                        <div class="slider-info">
                            <?php the_field('text_slider', $slider_post->ID) ?>
                        </div>
                        <a href="<?php the_field('link_slider', $slider_post->ID); ?>" class="slider-link" style="background-color: <?php the_field('button_slider_color', $slider_post->ID); ?>; color: <?php the_field('button_slider_color2', $slider_post->ID); ?>"><?php the_field('text_btn_slider', $slider_post->ID); ?></a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
        </div>
    </div>
<?php }
add_shortcode( 'slider', 'true_misha_func' );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-12-07
@hypero

The shortcode function should return the variable return , and not output echo as you currently have. This can be done in two ways
1. Declare an output buffer ob_start()and return it withob_get_contents()

function slider_shortcode_func( $atts ) { 
  ob_start(); ?>
  
  <div class="slider">
    <div class="slider-init">
      <h2>Slider Content</h2>
    </div>
  </div>

  <?php ob_get_contents();
}
add_shortcode( 'slider', 'slider_shortcode_func' );

2. Collect and return a variable using string concatenation
function slider_shortcode_func( $atts ) { 

  $html = '';

  $html .= '<div class="slider">';
    $html .= '<div class="slider-init">';
      $html .= '<h2>Slider Content</h2>';
    $html .= '</div>';
  $html .= '</div>';

  return $html;
}
add_shortcode( 'slider', 'slider_shortcode_func' );

In this case, the functions the_field()need to be rewritten in get_field()
PS. Once you pass ID to them $slider_post->ID, the function is setup_postdata()not needed by
PSS. Of course, the function getSlider()must return an array of records to work, nothing will work without it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question