Flutter Wordpress
此库使用 WordPress REST API V2 为您的应用程序提供与 WordPress 网站交互的方式。
要求
为了认证和使用管理员级别的REST API,您需要在您的WordPress站点中使用以下两种流行的认证插件
入门
1. 导入库
https://pub.dartlang.org/packages/flutter_wordpress
import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;
2. 实例化WordPress类
wp.WordPress wordPress;
// adminName and adminKey is needed only for admin level APIs
wordPress = wp.WordPress(
baseUrl: 'https://',
authenticator: wp.WordPressAuthenticator.JWT,
adminName: '',
adminKey: '',
);
3. 认证用户
Future<wp.User> response = wordPress.authenticateUser(
username: 'ChiefEditor',
password: 'chiefeditor@123',
);
response.then((user) {
createPost(user);
}).catchError((err) {
print('Failed to fetch user: $err');
});
4. 获取文章
Future<List<wp.Post>> posts = wordPress.fetchPosts(
params: wp.ParamsPostList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 20,
order: wp.Order.desc,
orderBy: wp.PostsOrderBy.date,
),
fetchAuthor: true,
fetchFeaturedMedia: true,
fetchComments: true,
);
5. 获取用户
Future<List<wp.User>> users = wordPress.fetchUsers(
params: wp.ParamsUserList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
order: wp.Order.asc,
orderBy: wp.UsersOrderBy.name,
role: wp.UserRole.subscriber,
),
);
6. 获取评论
Future<List<wp.Comment>> comments = wordPress.fetchComments(
params: wp.ParamsCommentList(
context: wp.WordPressContext.view,
pageNum: 1,
perPage: 30,
includePostIDs: [1],
),
);
7. 创建文章
void createPost(wp.User user) {
final post = wordPress.createPost(
post: new wp.Post(
title: 'First post as a Chief Editor',
content: 'Blah! blah! blah!',
excerpt: 'Discussion about blah!',
author: user.id,
commentStatus: wp.PostCommentStatus.open,
pingStatus: wp.PostPingStatus.closed,
status: wp.PostPageStatus.publish,
format: wp.PostFormat.standard,
sticky: true,
),
);
post.then((p) {
print('Post created successfully with ID: ${p.id}');
postComment(user, p);
}).catchError((err) {
print('Failed to create post: $err');
});
}
8. 发表评论
void postComment(wp.User user, wp.Post post) {
final comment = wordPress.createComment(
comment: new wp.Comment(
author: user.id,
post: post.id,
content: "First!",
parent: 0,
),
);
comment.then((c) {
print('Comment successfully posted with ID: ${c.id}');
}).catchError((err) {
print('Failed to comment: $err');
});
}
未来工作
- 实现OAuth 2.0认证。