Skip to content

Commit 991618c

Browse files
committed
add support for custom fields on posts
1 parent c7f4f49 commit 991618c

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

lib/flutter_wordpress.dart

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,9 @@ class WordPress {
246246
///
247247
/// [fetchAll] will make as many API requests as is needed to get all posts.
248248
/// This may take a while.
249+
///
250+
/// Specify any custom fields in [customFieldNames]. They will be loaded into
251+
/// [Post.customFields]
249252
///
250253
/// In case of an error, a [WordPressError] object is thrown.
251254
async.Future<List<Post>> fetchPosts({
@@ -259,7 +262,8 @@ class WordPress {
259262
bool fetchFeaturedMedia = false,
260263
bool fetchAttachments = false,
261264
String postType = "posts",
262-
bool fetchAll = false
265+
bool fetchAll = false,
266+
Set<String> customFieldNames = null
263267
}) async {
264268
if (fetchAll) {
265269
postParams = postParams.copyWith(perPage: 100);
@@ -276,9 +280,16 @@ class WordPress {
276280
List<Post> posts = new List();
277281
final list = json.decode(response.body);
278282

279-
for (final post in list) {
283+
for (final Map<String, dynamic> post in list) {
284+
Map<String, dynamic> customFields;
285+
286+
if (customFieldNames?.isNotEmpty ?? false) {
287+
customFields = Map.fromEntries(
288+
customFieldNames.map((key) => MapEntry(key, post[key])));
289+
}
290+
280291
posts.add(await _postBuilder(
281-
post: Post.fromJson(post),
292+
post: Post.fromJson(post)..customFields = customFields,
282293
setAuthor: fetchAuthor,
283294
setComments: fetchComments,
284295
orderComments: orderComments,

lib/schemas/post.dart

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,9 @@ class Post {
100100
/// The featured Media of the post.
101101
Media featuredMedia;
102102

103+
/// Custom fields on a post.
104+
Map<String, dynamic> customFields;
105+
103106
Post({
104107
this.date,
105108
this.dateGmt,
@@ -119,6 +122,7 @@ class Post {
119122
this.format = PostFormat.standard,
120123
this.categoryIDs,
121124
this.tagIDs,
125+
this.customFields,
122126
}) : this.title = new Title(rendered: title),
123127
this.featuredMedia = new Media(sourceUrl: featuredMedia),
124128
this.content = new Content(rendered: content),
@@ -208,6 +212,12 @@ class Post {
208212
if (this.categoryIDs != null)
209213
data['categories'] = listToUrlString(this.categoryIDs);
210214
if (this.tagIDs != null) data['tags'] = listToUrlString(this.tagIDs);
215+
if (customFields != null) {
216+
for (final key in customFields.keys) {
217+
data[key] = customFields[key];
218+
}
219+
}
220+
211221
return data;
212222
}
213223

0 commit comments

Comments
 (0)