php - Shortcode content output but not in correct place

admin2025-06-03  3

I have created a shortcode that gets information from an ACF repeater field...

function display_websites_shortcode() {

    ob_start();

    // check if the repeater field has rows of data
    if( have_rows('streaming') ):
        while ( have_rows('streaming') ) : the_row();

            // Your loop code          
            echo '<a href="' . the_sub_field('website_url') . '" >' . the_sub_field('website_source') . '</a>';     

        endwhile;
    else :
        // no rows found        
        echo '<p>No Websites Available</p>';            
    endif;

    return ob_get_clean();
}   
add_shortcode( 'display_websites', 'display_websites_shortcode' );

The output/loop works but the content is outside the HTML. So, instead of this...

<a href="">Google</a>

We get this...

I have other shortcodes working using similar code, I just can't figure this out. I've checked other posts with similar issues but nothing stands out

I have created a shortcode that gets information from an ACF repeater field...

function display_websites_shortcode() {

    ob_start();

    // check if the repeater field has rows of data
    if( have_rows('streaming') ):
        while ( have_rows('streaming') ) : the_row();

            // Your loop code          
            echo '<a href="' . the_sub_field('website_url') . '" >' . the_sub_field('website_source') . '</a>';     

        endwhile;
    else :
        // no rows found        
        echo '<p>No Websites Available</p>';            
    endif;

    return ob_get_clean();
}   
add_shortcode( 'display_websites', 'display_websites_shortcode' );

The output/loop works but the content is outside the HTML. So, instead of this...

<a href="http://google">Google</a>

We get this...

http://googleGoogle

I have other shortcodes working using similar code, I just can't figure this out. I've checked other posts with similar issues but nothing stands out

Share Improve this question asked Feb 18, 2019 at 19:49 Stuart MoirStuart Moir 132 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 2

The problem is that in 99% of cases, the_*() functions will echo out the content. If you're assigning them you would need to use get_*() functions.

In your case you're echoing twice, once at the beginning of the link and again with the_*() function in the attribute and between the opening and closing tags. It breaks the string concatenation you have in place by echoing more than once.

Your code should look like:

echo '<a href="' . get_sub_field('website_url') . '" >' . get_sub_field('website_source') . '</a>';
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748893203a314598.html

最新回复(0)