在您的案例中列出自定义分类的术语books
我们需要为JSON API创建一个自定义控制器。
Step 1: 应将以下2个类粘贴到存储在主题目录中的php文件中(您可以将文件存储在任何您喜欢的地方,但您必须确保在中的代码中返回文件的正确路径Step 2). 此示例的文件名为:json-api-taxonomy-index.php
<?php
/**
* JSON API custom taxonomy index
**/
/**
* Custom Taxonomy Controller for JSON API plugin
*
* This custom taxonomy controller enables json api to list all terms in specified taxonomy.
**/
class JSON_API_Taxonomy_Controller {
public function get_taxonomy_index() {
$terms = $this->get_terms();
return array(
\'count\' => count( $terms ),
\'terms\' => $terms
);
}
public function get_terms() {
global $json_api;
$taxonomy = $this->get_current_taxonomy();
if (!$taxonomy) {
$json_api->error("Not found.");
}
$wp_terms = get_terms( $taxonomy );
$terms = array();
foreach ( $wp_terms as $wp_term ) {
if ( $wp_term->term_id == 1 && $wp_term->slug == \'uncategorized\' ) {
continue;
}
$terms[] = new JSON_API_Term( $wp_term );
}
return $terms;
}
protected function get_current_taxonomy() {
global $json_api;
$taxonomy = $json_api->query->get(\'taxonomy\');
if ( $taxonomy ) {
return $taxonomy;
} else {
$json_api->error("Include \'taxonomy\' var in your request.");
}
return null;
}
}
// Generic rewrite of JSON_API_Tag class to represent any term of any type of taxonomy in WP
class JSON_API_Term {
var $id; // Integer
var $slug; // String
var $title; // String
var $description; // String
function JSON_API_Term($term = null) {
if ($term) {
$this->import_wp_object($term);
}
}
function import_wp_object($term) {
$this->id = (int) $term->term_id;
$this->slug = $term->slug;
$this->title = $term->name;
$this->description = $term->description;
$this->post_count = (int) $term->count;
}
}
?>
Step 2: 在函数中粘贴以下过滤器。php文件。如果尚未将文件存储在主题目录中,请在中更改文件的路径
set_taxonomy_controller_path
作用
function add_taxonomy_controller($controllers) {
$controllers[] = \'Taxonomy\';
return $controllers;
}
add_filter(\'json_api_controllers\', \'add_taxonomy_controller\');
function set_taxonomy_controller_path() {
return get_stylesheet_directory() . \'/json-api-taxonomy-index.php\';
}
add_filter(\'json_api_taxonomy_controller_path\', \'set_taxonomy_controller_path\');
Step 3: 转到
Settings->JSON API
并激活分类控制器。
就这样,你完了!现在,您可以使用json api访问自定义分类法的术语。示例:http://example.com/api/Taxonomy/get_taxonomy_index/?taxonomy=books