从循环外部获取自定义分类的自定义元

时间:2019-01-31 00:18:16

标签: php wordpress

我为自定义分类法创建了许多自定义字段。在查询中拉出它们的值没有问题。但是在这种情况下,我让他们重复了此分类法中发帖的次数。

这是循环内的代码

$tables_terms = $atts['custom'];

$tabargs = array(
    'posts_per_page' => -1,
    'offset'         => 0,   
    'post_type'      => 'customtables',
    'tax_query'     => array(
          array(
            'taxonomy' => 'tables', 
            'field' => 'slug',
            'terms' => array( 
                $tables_terms
            )
          )
        )
);

$tabs = new WP_Query( $tabargs );


if( $tabs->have_posts() ){
    while( $tabs->have_posts() ) : $tabs->the_post();
        $terms = get_the_terms( get_the_ID(), 'tables' );
        foreach ( $terms as $term ) {
            $t_id = $term->term_id;
            $term_meta = get_option( "taxonomy_$t_id" );
            echo $term_meta['term_1'];
        }   
    endwhile;
    wp_reset_postdata();
    echo $custom;
}

如何让它们在循环外显示一次?

3 个答案:

答案 0 :(得分:0)

您可以使用get_term_meta;

get_term_meta检索元数据的术语。

get_term_meta( $term->term_id, 'your_term_name', true )

答案 1 :(得分:0)

因此以下代码实际上对我有用

$term_slug = $tables_terms;
$taxonomies = get_taxonomies();
foreach ( $taxonomies as $tax_type_key => $taxonomy ) {
    if ( $term_object = get_term_by( 'slug', $term_slug , $taxonomy ) ) {
        break;
    }
}
$t_id = $term_object->term_id;
$term_meta = get_option( "taxonomy_$t_id" );

然后,我只是像这样回显每个元数据

echo $term_meta['term_1'];

答案 2 :(得分:0)

那样尝试:

存储您输出一个阵列中,并检查时存储其该值已经存在与否。

$tables_terms = $atts['custom'];

$tabargs = array(
'posts_per_page' => -1,
'offset'         => 0,   
'post_type'      => 'customtables',
'tax_query'     => array(
      array(
        'taxonomy' => 'tables', 
        'field' => 'slug',
        'terms' => array( 
            $tables_terms
        )
      )
    )
    );

  $tabs = new WP_Query( $tabargs );

  $term_meta_array = array();
  if( $tabs->have_posts() ){
  while( $tabs->have_posts() ) : $tabs->the_post();
    $terms = get_the_terms( get_the_ID(), 'tables' );

    foreach ( $terms as $term ) {
        $t_id = $term->term_id;
        $term_meta = get_option( "taxonomy_$t_id" );
        echo $term_meta['term_1'];
        if(!in_array($term_meta['term_1'], $term_meta_array)) array_push($$term_meta_array, $term_meta['term_1']);
    }   
  endwhile;
  wp_reset_postdata();
  echo $custom;
  foreach($term_meta_array as $st){
  echo $st;
}
}