dousongqiang2585 2011-06-10 21:29
浏览 32
已采纳

在shortcode中返回foreach内部

I'm using the PHP code below to display CSS classes based on the custom taxonomies applied to my WordPress posts. My taxonomy is called CC and its three options are x, y, and z. For a post that has all three:

 $cc_terms = get_the_terms($post->ID,'cc');
 foreach ($cc_terms as $term) { 
     echo ' '.$term->slug.'-active'; 
 }

outputs: x-active y-active z-active

I'm trying to convert it into WordPress shortcode function (where echo doesn't work as far as I know) and basically I need to figure out how to capture cc_class() as one variable (not an array) so that it give me the same output as above.

function cc_meta($atts, $content = null) {
    global $post;
    extract(shortcode_atts(array('class' => 'default'), $atts));
    function cc_class() {
        $cc_terms = get_the_terms($post->ID, 'cc');
        foreach($cc_terms as $term) {
            return ' '.$term->slug.'-active';
        }
    }
    return '<div class="' . esc_attr($class) . cc_class() . '">...</div>';
}

outputs: <div class="default x-active">...</div>

It's only taking the first term rather than all three, which makes me wonder how return works in foreach loops. Any idea how I can get this to work?

desired output: <div class="default x-active y-active z-active">...</div>

Update 1: I tried with the .= as suggested and I'm getting a blank error:

function cc_meta( $atts, $content = null ) {
    global $post;
    extract(shortcode_atts(array('class' => 'default'), $atts));

    $cc_terms = get_the_terms($post->ID, 'cc');
    foreach ($cc_terms as $term) {
        $return .= ' '.$term->slug.'-active';
    }
    return '<div class="' . esc_attr($class) . $return . '">...</div>';
}

Update 2: I removed the global $post line and it works—sweet! Thanks everyone =)

function cc_meta($atts, $content = null) {
    extract(shortcode_atts(array('class' => 'default'), $atts));
    $cc_terms = get_the_terms($post->ID, 'cc');
    foreach($cc_terms as $term) { 
        $return .= ' '.$term->slug.'-active';
    }
    return '<div class="' . esc_attr($class) . $return . '">...</div>';
}
  • 写回答

1条回答 默认 最新

  • dsm1998 2011-06-10 21:34
    关注

    Don't return in the middle of your function, use return only at the end.

    Instead of return use this:

    $return .= 
    

    and before the closing } do a return $return;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?