Remove echo from shortcode

时间:2014-08-05 作者:ngearing

我刚刚开始使用短代码,由于缺乏php知识,我无法想出如何在不使用php echo的情况下使用此短代码。

有人能帮我修改代码吗?

// 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");

1 个回复
最合适的回答,由SO网友:Chinmoy Kumar Paul 整理而成

“echo”语句在shortcode函数中不起作用。shortcode函数只是返回变量;因此,您的代码如下所示:

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;

结束