Search code examples
phpwordpressadvanced-custom-fields

displaying ACF repeater fields as shordcode in functions.php


I have a wordpress and ACF related question. I need to display repeater field as a shortcode that will be created inside functions.php file. Then I will use shortcode inside post page with Gutenberg. Is this possible?

I struggle with this today and I can`t find a solution :(

<?php if ( have_rows( 'car_parts' ) ) : ?>  /* this is repeater field */
    <?php while ( have_rows( 'car_parts' ) ) : the_row(); ?>
        <?php the_sub_field( 'car_engine' ); ?>  /* this is repeater subfield */
    <?php endwhile; ?>
<?php else : ?>
    <?php // No rows found ?>
<?php endif; ?>


I prepared a function called

function get_car_parts() {
    echo 'display ACF repeater fields here';
}
    
add_shortcode( 'show-car-parts', 'get_car_parts' );

Any help greatly appreciated :-)


Solution

  • The callback in add_shortcode function should not return an output of any kind, just return the text that is to be used to replace the shortcode, like this:

    <?php
    function get_car_parts()
    {
      if (have_rows('car_parts')): /* this is repeater field */
        while (have_rows('car_parts')):
            the_row();
            $car_engine = the_sub_field('car_engine'); /* this is repeater subfield */
       endwhile;
        return $car_engine;
      else:
        return "No rows found";
      endif;
    }
    
    add_shortcode('show-car-parts', 'get_car_parts');