1

I've just started playing with shortcodes and due to my lack of php knowledge I am unable to figure out how to make this shortcode work without using php echo.

Can anyone help me revise my code?

// SPONSORS Shorcode

function sponsors_shortcode($atts) {

extract(shortcode_atts(array(
    "name" => "sponsors",
), $atts));

$args = array(
    "post_type" => "sponsors",
    "name" => $name,
);
$query = new WP_Query($args);

if($query->have_posts()) : while($query->have_posts()) : $query->the_post();

if(get_field('group')) {

    echo "<ul class='sponsors'><h2>" , the_title() , "</h2>";

    while(has_sub_field('group')) {

        $attachment_id = get_sub_field('image'); 
        $size = 'sponsorimage'; 
        $image = wp_get_attachment_image_src( $attachment_id, $size , false );

        $link = get_sub_field('link');

        echo "<li>";
            echo "<a href='" , $link , "' target='_blank'>";
                echo "<img src='" , $image[0] , "' />";
            echo "</a>";
        echo "</li>";
    }
    echo "</ul>";
}


endwhile; endif; wp_reset_query();

}

add_shortcode("sponsors", "sponsors_shortcode");
0

'echo' statement will not work in shortcode function. shortcode function is just returning the variable; So your code will be like this:

if(get_field('group')) {
    $html = '';
    $html.= "<ul class='sponsors'><h2>" , get_the_title() , "</h2>";

    while(has_sub_field('group')) {

        $attachment_id = get_sub_field('image'); 
        $size = 'sponsorimage'; 
        $image = wp_get_attachment_image_src( $attachment_id, $size , false );

        $link = get_sub_field('link');

        $html.= "<li>";
        $html.= "<a href='" , $link , "' target='_blank'>";
        $html.= "<img src='" , $image[0] , "' />";
        $html.= "</a>";
        $html.= "</li>";
    }
    $html.= "</ul>";
}
endwhile; endif; wp_reset_query();

return $html;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.