首页 视频课程 主题开发课程第21章、REST API WordPress REST API 站点接口详细情况

WordPress REST API 站点接口详细情况

2023-06-11 / 231阅

WordPress REST API 站点接口详细情况

WordPress REST API 是一种通过 HTTP 协议访问 WordPress 数据的方式。它使得开发人员可以利用现代的 Web 技术构建与 WordPress 相关的应用程序,例如移动应用,JavaScript 应用程序,桌面应用程序等。

REST API 站点接口

REST API 站点接口是 WordPress REST API 的一部分,它提供了访问 WordPress 站点的端点。

以下是 WordPress REST API 站点接口的一些常见用法和示例代码:

获取站点基本信息

获取站点的基本信息,例如站点标题,站点描述等。

$url = 'https://example.com/wp-json';
$response = wp_remote_get( $url );

if ( is_array( $response ) ) {
    $headers = $response['headers'];
    $body    = $response['body'];
}

$site_info = json_decode( $body ); 

获取所有文章

获取网站上所有文章的列表。

$url = 'https://example.com/wp-json/wp/v2/posts';
$response = wp_remote_get( $url );

if ( is_array( $response ) ) {
    $headers = $response['headers'];
    $body    = $response['body'];
}

$posts = json_decode( $body ); 

获取单篇文章

获取指定文章的详细信息。

$post_id = 1;
$url = 'https://example.com/wp-json/wp/v2/posts/' . $post_id;
$response = wp_remote_get( $url );

if ( is_array( $response ) ) {
    $headers = $response['headers'];
    $body    = $response['body'];
}

$post = json_decode( $body ); 

创建文章

使用 WordPress REST API 创建一篇新文章。

$token = 'abcdefghijklmopqrstuvwxyz';
$url = 'https://example.com/wp-json/wp/v2/posts';
$fields = array(
    'title'   => 'New Post Title',
    'content' => 'New Post Content',
    'status'  => 'publish'
);
$headers = array(
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer ' . $token
);
$args = array(
    'headers' => $headers,
    'body'    => json_encode( $fields ),
    'method'  => 'POST'
);
$response = wp_remote_post( $url, $args );

if ( is_array( $response ) ) {
    $headers = $response['headers'];
    $body    = $response['body'];
}

$new_post = json_decode( $body ); 

编辑文章

使用 WordPress REST API 编辑一篇现有文章。

$token = 'abcdefghijklmopqrstuvwxyz';
$post_id = 1;
$url = 'https://example.com/wp-json/wp/v2/posts/' . $post_id;
$fields = array(
    'title'   => 'Updated Post Title',
    'content' => 'Updated Post Content',
);
$headers = array(
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer ' . $token
);
$args = array(
    'headers' => $headers,
    'body'    => json_encode( $fields ),
    'method'  => 'POST'
);
$response = wp_remote_post( $url, $args );

if ( is_array( $response ) ) {
    $headers = $response['headers'];
    $body    = $response['body'];
}

$updated_post = json_decode( $body ); 

删除文章

使用 WordPress REST API 删除一篇现有文章。

$token = 'abcdefghijklmopqrstuvwxyz';
$post_id = 1;
$url = 'https://example.com/wp-json/wp/v2/posts/' . $post_id;
$headers = array(
    'Authorization' => 'Bearer ' . $token
);
$args = array(
    'headers' => $headers,
    'method'  => 'DELETE'
);
$response = wp_remote_post( $url, $args ); 

总结

WordPress REST API 站点接口提供了一种便捷的方法来访问 WordPress 数据,使得我们可以轻松地构建与 WordPress 相关的应用程序。在实际开发中,可以根据具体需求进行调用,实现所需的功能。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录