php WordPress REST API配方
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php WordPress REST API配方相关的知识,希望对你有一定的参考价值。
<?php
/**
* Really simple GET request
*/
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) {
register_rest_route( '/custom-namespace/v1', '/no-param', [
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
if ( $throw_error = false ) {
return new WP_Error( 'some-error-code', 'There was an error', [
'heres' => 'some',
'error' => 'data'
] );
} else {
return new WP_REST_Response( [
'here' => 'is',
'some' => 'data'
], 200 );
}
}
] );
} );
/**
* Really simple GET request that accepts an integer as a parameter/arg
*/
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) {
register_rest_route( '/custom-namespace/v1', '/numeric-param/(?P<numeric_param>[\d]+)', [
'args' => [
'numeric_param' => [
'description' => __( 'Some numberic parameter' ),
'type' => 'integer'
],
],
[
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
if ( $throw_error = false ) {
return new WP_Error( 'some-error-code', 'There was an error', [
'heres' => 'some',
'error' => 'data'
] );
} else {
return new WP_REST_Response( [
'here' => 'is',
'some' => 'data',
'using' => 'provided',
'arg' => $request->get_param( 'numeric_param' )
], 200 );
}
}
]
] );
} );
/**
* Really simple GET request that accepts a string as a parameter/arg
*/
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) {
register_rest_route( '/custom-namespace/v1', '/string-param/(?P<string_param>[a-zA-Z0-9_-]+)', [
'args' => [
'string_param' => [
'description' => __( 'Some string arg' ),
'type' => 'string'
],
],
[
'methods' => 'GET',
'callback' => function ( WP_REST_Request $request ) {
if ( $throw_error = false ) {
return new WP_Error( 'some-error-code', 'There was an error', [
'heres' => 'some',
'error' => 'data'
] );
} else {
return new WP_REST_Response( [
'here' => 'is',
'some' => 'data',
'using' => 'provided',
'arg' => $request->get_param( 'string_param' )
], 200 );
}
}
]
] );
} );
以上是关于php WordPress REST API配方的主要内容,如果未能解决你的问题,请参考以下文章
php Wordpress REST API基础知识
php 用于WordPress的SAAS REST API
php Wordpress在WP REST API上添加自定义帖子类型
wordpress rest api 授权
WordPress插件:使用REST API
无法在 Wordpress 中使用 REST API 获得响应