如何遍历这些数据?

时间:2019-05-20 12:23:54

标签: wordpress

我正在尝试从get_terms_by()返回的数据中获取术语ID。

WP_Term Object ( [term_id] => 29 [name] => gps [slug] => gps [term_group] => 0 [term_taxonomy_id] => 29 [taxonomy] => post_tag [description] => [parent] => 0 [count] => 1 [filter] => raw )
 WP_Term Object ( [term_id] => 16 [name] => joystick [slug] => joystick [term_group] => 0 [term_taxonomy_id] => 16 [taxonomy] => post_tag [description] => [parent] => 0 [count] => 3 [filter] => raw )
 WP_Term Object ( [term_id] => 14 [name] => lcd [slug] => lcd [term_group] => 0 [term_taxonomy_id] => 14 [taxonomy] => post_tag [description] => [parent] => 0 [count] => 3 [filter] => raw )

但是它以字符串形式返回数据

$data = get_term_by('name', $tag , 'post_tag');
print_r($data);

foreach ($data as $tag_id) {
    echo $tag_id['term_id'];
}

我想要这个[term_id] => 29 只有term_id

2 个答案:

答案 0 :(得分:0)

函数get_term_by具有一个名为$output的参数。如果指定它,则应该返回一个数组:

$term = get_term_by( 'name', $tag, 'post_tag' );

if ( $term ) {
    echo $term->term_id;
}
else {
    echo 'Term not found';
}

答案 1 :(得分:0)

首先,您不能只得到[term_id] => 291,因为结果有3个条件,所以可以有数组$term_ids = array(29, 16, 14);

$data = get_term_by('name', $tag , 'post_tag');
$term_ids = array();

foreach ($data as $term) {
    $term_ids[] = $term->term_id;
}

print_r($term_ids);