如何以JSON格式列出类别和子类别?

时间:2013-01-16 作者:Amino

我需要整合this plugin 使用我的WordPress网站,类别必须采用以下格式:

 "Option 1": {"Suboption":200},
 "Option 2": {"Suboption 2": {"Subsub 1":201, "Subsub 2":202},
                "Suboption 3": {"Subsub 3":203, "Subsub 4":204, "Subsub 5":205}
               }
我怎样才能得到它<我尝试了json-api.

这是步行者:

class MyWalker extends Walker_Category {
    var $tree_type = \'category\';

    var $db_fields = array (\'parent\' => \'parent\', \'id\' => \'term_id\');

    function start_lvl( &$output, $depth, $args = array() ) {
        if ( \'list\' != $args[\'style\'] )
            return;

        $indent = str_repeat("\\t", $depth);
        $output .= "$indent:{";
    }

    function end_lvl( &$output, $depth, $args = array() ) {
        if ( \'list\' != $args[\'style\'] )
            return;

        $indent = str_repeat("\\t", $depth);
        $output .= "$indent}\\n";
    }

    function start_el($output, $category, $depth , $args = array() ) {
        extract($args);
        $cat_name = esc_attr( $category->name );
        $cat_name = apply_filters( \'list_cats\', $cat_name, $category );
        $output .= \'"\' . $cat_name.\'=>\'.$depth . \'",\';
    }

    function end_el($output, $page, $depth = 0, $args = array() ) {
        if ( \'list\' != $args[\'style\'] )
            return;

        $output .= "\\n";
    }
}

2 个回复
最合适的回答,由SO网友:Wyck 整理而成

下面是一个使用get_categories 它将以json格式列出父类别的所有子类别,而不是插件或walker类,可能会帮助您朝着正确的方向发展。正如brasofilo所提到的,因为您需要特定的格式,所以您需要构建一个自定义数组。

// let\'s get the bare minimum going
$args = array(
    \'type\'                     => \'post\',
    \'child_of\'                 =>  20, //change this, hardcoded as example
    \'taxonomy\'                 =>  \'category\'
);

$categories = get_categories( $args );
$json = json_encode($categories);

var_dump($json); //do what you want

SO网友:Marcelo Ribeiro
$args = [
    \'taxonomy\' => \'category\',
    \'hide_empty\' => 0,
    \'parent\' => 0
];

function _get_child_terms( $items ) {
    foreach ( $items as $item ) {
      $item->children = get_terms( \'category\', array( \'child_of\' => $item->term_id, \'hide_empty\' => 0 ) );
      if ( $item->children ) _get_child_terms( $item->children );
    }
    return $items;
}

$terms = _get_child_terms( get_terms( $args ) );
echo json_encode( $terms );
结束