Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Help me debug this shortcode WordPress

  • SOLVED

Hi WP Questions,

I have made the following shortcode in functions.php for use with Advanced Custom Fields.

The shortcode works, but the content is being outputted in the top of the page instead of where the shortcode is.

I guess it's something pretty basic, but I cannot seem to figure it out.

It's setup like this.
1) I have a repeater field in Advanced Custom Fields called "links".
2) Inside that repeater field I have a normal text field called "link".

Here is the shortcode:
function acf_link_shortcode() {

if( have_rows('links') ):

while( have_rows('links') ): the_row(); ?>

<a href=" <?php the_sub_field('link', $post->ID); ?> " target="_blank"> <?php the_sub_field('link', $post->ID); ?> </a>

<?php endwhile;

endif;

}
add_shortcode( 'acf_link', 'acf_link_shortcode' );

Answers (1)

2017-01-31

Rempty answers:

try this
function acf_link_shortcode() {
global $post;
if( have_rows('links') ):

while( have_rows('links') ): the_row();
ob_start();
?>
<a href=" <?php the_sub_field('link', $post->ID); ?> " target="_blank"> <?php the_sub_field('link', $post->ID); ?> </a>
<?php
$text = ob_get_contents();
endwhile;
endif;
ob_end_clean();
return $text;
}
add_shortcode( 'acf_link', 'acf_link_shortcode' );


medico comments:

Thanks, besides that I had to move "ob_start();" up above the "while( have_rows('links') ): the_row();" this code works great.


Rempty comments:

Just a comment
The shortcodes functions can't echo directly the html, you need to return a variable with the html code.
This is why assigned the result to a variable, using ob_start i am capturing the code and storing in a variable.