如何将 css 类添加到我的示例 php 代码中

我想在这段php代码的输出中添加一个类


function acf_esg_tax_field_loc( $atts, $content = null ) {

    $a = shortcode_atts(array('post_id' => "1"), $atts);

    $term = get_field( "field_56cb3d84cf32a", $a['post_id'] );


    echo $term->name;

}


add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );


该代码用于我的 Wordpress 函数 php 以生成短代码。


它应该是这样的


function acf_esg_tax_field_loc( $atts, $content = null ) {

    $a = shortcode_atts(array('post_id' => "1"), $atts);

    $term = get_field( "field_56cb3d84cf32a", $a['post_id'] );


    echo '<div class="OutputClass" >';

    echo $term->name;

    echo '</div>'; 

}


add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );

不幸的是,这不起作用。


你能帮忙吗?


江户川乱折腾
浏览 170回答 2
2回答

皈依舞

正如WordPress 代码参考所述。请注意,短代码调用的函数不应产生任何类型的输出。短代码函数应返回用于替换短代码的文本。直接产生输出会导致意想不到的结果。这类似于过滤器函数的行为方式,因为它们不应该从调用中产生预期的副作用,因为您无法控制调用它们的时间和地点。所以先把它从 echo 改为 one return。您可以定义一个变量,连接到它并最终返回它。结果:function acf_esg_tax_field_loc( $atts, $content = null ) {&nbsp; &nbsp; $a = shortcode_atts(array('post_id' => "1"), $atts);&nbsp; &nbsp; $term = get_field( "field_56cb3d84cf32a", $a['post_id'] );&nbsp; &nbsp; $sR =&nbsp; '<div class="OutputClass" >';&nbsp; &nbsp; $sR .= $term->name;&nbsp; &nbsp; $sR .= '</div>';&nbsp;&nbsp; &nbsp; return $sR;}add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );

莫回无

如果类始终相同,因此可以进行硬编码,那么您就非常接近了。只会输出一个回声,所以将它连接起来:echo&nbsp;'<div&nbsp;class="OutputClass"&nbsp;>'.$term->name.'</div>';如果它是动态的,并且您需要在某处获取类名并将其传递,那么情况就完全不同了。
打开App,查看更多内容
随时随地看视频慕课网APP