为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
江户川乱折腾 2021-06-15 09:45:37
我想在这段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' );不幸的是,这不起作用。你能帮忙吗?
查看完整描述

2 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

正如WordPress 代码参考所述。


请注意,短代码调用的函数不应产生任何类型的输出。短代码函数应返回用于替换短代码的文本。直接产生输出会导致意想不到的结果。这类似于过滤器函数的行为方式,因为它们不应该从调用中产生预期的副作用,因为您无法控制调用它们的时间和地点。


所以先把它从 echo 改为 one return。您可以定义一个变量,连接到它并最终返回它。


结果:


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'] );


    $sR =  '<div class="OutputClass" >';

    $sR .= $term->name;

    $sR .= '</div>'; 

    return $sR;

}


add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );


查看完整回答
反对 回复 2021-06-19
?
莫回无

TA贡献1865条经验 获得超7个赞

如果类始终相同,因此可以进行硬编码,那么您就非常接近了。只会输出一个回声,所以将它连接起来:

echo '<div class="OutputClass" >'.$term->name.'</div>';

如果它是动态的,并且您需要在某处获取类名并将其传递,那么情况就完全不同了。


查看完整回答
反对 回复 2021-06-19
  • 2 回答
  • 0 关注
  • 169 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信