0

I have a loop to get a list of terms for a taxonomy.

    <?php 
  $terms = get_field('modell');
  if( $terms ):
    $total = count($terms);
    $count = 1;
    foreach( $terms as $term ):
      ?>
      '<?php echo $term->slug; ?>'
      <?php 
      if ($count < $total) {
        echo ', ';
      }
      $count++;
    endforeach;
  endif; 
?>

The loop output is this:

 'termname-one','termname-two','termname-three' 

Now I want to save this output into variable ($termoutput) and insert it into a array of terms of following loop:

<?php 
query_posts( array(  
    'post_type' => 'posttypename', 
    'posts_per_page' => -1, 
    'orderby' => 'title',
    'order' => 'ASC',
    'tax_query' => array( 
       array( 
          'taxonomy' => 'systems', 
          'field' => 'slug', 
         'terms' => array($termoutput)
       ) 
   ) 

) );    ?>

Is there a way to achive this? Thank you!

1
  • $termoutput = []; before the foreach. Then in your loop instead of echo use $termoutput[] = $term->slug;... that's literally it. Commented Oct 18, 2017 at 12:13

2 Answers 2

2

You should accumulate your output into an array like this:

$termoutput = array();

...

foreach( $terms as $term ) {
    $termoutput[] = $term->slug;
}

Then, in the second section of your code:

...
'terms' => $termoutput
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

 <?php 
  $terms = get_field('modell');
  if( $terms ):
    $total = count($terms);
    $count = 1;
    $termoutput = array();
    foreach( $terms as $term ):

      echo "'".$term->slug."'"; 
      $termoutput[] = $term->slug;

      if ($count < $total) {
        echo ', ';
      }
      $count++;
    endforeach;
  endif; 
?>


<?php 
    query_posts( array(  
        'post_type' => 'posttypename', 
        'posts_per_page' => -1, 
        'orderby' => 'title',
        'order' => 'ASC',
        'tax_query' => array( 
          array( 
              'taxonomy' => 'systems', 
              'field' => 'slug', 
             'terms' => $termoutput
           ) 
       ) 

    ) );    
 ?>

This will store $term->slug to $termoutput[] as an array.

2 Comments

This will throw a warning in some cases because you haven't preset $termoutput as an array before the loop. Add $termoutput = array(); before the foreach.
@naththedeveloper sorry forgot about that, was busy editing his code. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.