Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn inside foreach inside shortcode
    text
    copied!<p>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:</p> <pre><code> $cc_terms = get_the_terms($post-&gt;ID,'cc'); foreach ($cc_terms as $term) { echo ' '.$term-&gt;slug.'-active'; } </code></pre> <p>outputs: x-active y-active z-active</p> <p>I'm trying to convert it into WordPress shortcode function (where <code>echo</code> doesn't work as far as I know) and basically I need to figure out how to capture <code>cc_class()</code> as one variable (not an array) so that it give me the same output as above. </p> <pre><code>function cc_meta($atts, $content = null) { global $post; extract(shortcode_atts(array('class' =&gt; 'default'), $atts)); function cc_class() { $cc_terms = get_the_terms($post-&gt;ID, 'cc'); foreach($cc_terms as $term) { return ' '.$term-&gt;slug.'-active'; } } return '&lt;div class="' . esc_attr($class) . cc_class() . '"&gt;...&lt;/div&gt;'; } </code></pre> <p>outputs: <code>&lt;div class="default x-active"&gt;...&lt;/div&gt;</code></p> <p>It's only taking the first term rather than all three, which makes me wonder how <code>return</code> works in <code>foreach</code> loops. Any idea how I can get this to work? </p> <p>desired output: <code>&lt;div class="default x-active y-active z-active"&gt;...&lt;/div&gt;</code></p> <p><strong>Update 1</strong>: I tried with the <code>.=</code> as suggested and I'm getting a blank error:</p> <pre><code>function cc_meta( $atts, $content = null ) { global $post; extract(shortcode_atts(array('class' =&gt; 'default'), $atts)); $cc_terms = get_the_terms($post-&gt;ID, 'cc'); foreach ($cc_terms as $term) { $return .= ' '.$term-&gt;slug.'-active'; } return '&lt;div class="' . esc_attr($class) . $return . '"&gt;...&lt;/div&gt;'; } </code></pre> <p><strong>Update 2</strong>: I removed the <code>global $post</code> line and it works—sweet! Thanks everyone =)</p> <pre><code>function cc_meta($atts, $content = null) { extract(shortcode_atts(array('class' =&gt; 'default'), $atts)); $cc_terms = get_the_terms($post-&gt;ID, 'cc'); foreach($cc_terms as $term) { $return .= ' '.$term-&gt;slug.'-active'; } return '&lt;div class="' . esc_attr($class) . $return . '"&gt;...&lt;/div&gt;'; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload