Get_Terms()返回空数组

时间:2015-01-17 作者:bypatryk

我已经阅读了所有关于显示自定义分类法术语的帖子,但它仍然不起作用。好的,下面是代码:

<?php
//part of template-offer.php
$taxonomy = \'brand\';
$term_args=array(
  \'hide_empty\' => false,
  \'orderby\' => \'name\',
  \'order\' => \'ASC\'
);
$tax_terms = get_terms($taxonomy,$term_args);
echo $tax_terms;
?>
在输出上,我只得到一个空数组。我盯着代码看,不知道为什么。我的自定义帖子和分类法都很有效,创建了一些帖子和术语:

<?php
//creating a custom taxonomy called \'brand\'
add_action( \'init\', \'create_custom_taxonomies\', 0 );
function create_custom_taxonomies() {
    $labels = array(
        \'name\'              => _x( \'Brands\', \'taxonomy general name\' ),
        \'singular_name\'     => _x( \'Brand\', \'taxonomy singular name\' ),
        \'search_items\'      => __( \'Search Brands\' ),
        \'all_items\'         => __( \'All Brands\' ),
        \'parent_item\'       => __( \'Parent Brand\' ),
        \'parent_item_colon\' => __( \'Parent Brand:\' ),
        \'edit_item\'         => __( \'Edit Brand\' ),
        \'update_item\'       => __( \'Update Brand\' ),
        \'add_new_item\'      => __( \'Add New Brand\' ),
        \'new_item_name\'     => __( \'New Brand Name\' ),
        \'menu_name\'         => __( \'Brand\' ),
    );
    $args = array(
        \'hierarchical\'      => true,
        \'labels\'            => $labels,
        \'show_ui\'           => true,
        \'show_admin_column\' => true,
        \'query_var\'         => true,
        \'rewrite\'           => array( \'slug\' => \'brand\' ),
    );
    register_taxonomy( \'brand\', null , $args );
}


//creating a custom post type that is using \'brand\' taxonomy
function create_post_type() {
    register_post_type( \'products\',
        array(
        \'labels\' => array(
            \'name\' => __( \'Products\' ),
            \'singular_name\' => __( \'Product\' ),
            \'add_new\' => _x(\'Add New\', \'products\'),
            \'add_new_item\' => __(\'Add New Product\'),
            \'edit_item\' => __(\'Edyt Product\'),
            \'new_item\' => __(\'New Product\'),
            \'view_item\' => __(\'View Product\'),
            \'search_items\' => __(\'Search Product\'),
            \'not_found\' =>  __(\'Nothing found\'),
        ),
        \'taxonomies\' => array(\'brand\'),
        \'supports\' => array(\'title\', \'editor\', \'thumbnail\'),
        \'public\' => true,
        \'has_archive\' => true,
        \'show_ui\' => true,
        )
    );

}
add_action( \'init\', \'create_post_type\' );
?>
我们将非常感谢您的帮助。祝你愉快Patryk

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

get_terms 返回array of objects. 你不能回显一个数组,如果你这样做,你只会得到Array(). 你能做的是print_r($array)var_dump($array)echo json_encode($array) 查看其中包含的数据。

否则,要从对象中获取单个元素(例如名称),需要传递$tax_terms 通过foreach 循环以从每个术语中获取对象,然后从那里您还可以回显您要查找的特定对象

像这样的东西会有用的

$tax_terms = get_terms( $taxonomy, $args );

foreach ( $tax_terms as $tax_term ) {

    echo $tax_term->name;

}

结束