将循环输出保存到变量中

时间:2017-10-18 12:08:57

标签: php wordpress advanced-custom-fields

我有一个循环来获取分类法的术语列表。

    <?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; 
?>

循环输出为:

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

现在我想将此输出保存到变量( $ termoutput )并将其插入以下循环的术语数组中:

<?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)
       ) 
   ) 

) );    ?>

有没有办法实现这个目标?谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

 <?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
           ) 
       ) 

    ) );    
 ?>

这会将 $ term-&gt; slug 存储为 $ termoutput [] 作为数组。

答案 1 :(得分:2)

您应该将输出累积到这样的数组中:

$termoutput = array();

...

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

然后,在代码的第二部分:

...
'terms' => $termoutput