Skip to content

Commit faf2d8f

Browse files
committed
add support for custom fields on posts
1 parent 62fa89d commit faf2d8f

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

lib/flutter_wordpress.dart

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,9 @@ class WordPress {
257257
///
258258
/// [fetchAll] will make as many API requests as is needed to get all posts.
259259
/// This may take a while.
260+
///
261+
/// Specify any custom fields in [customFieldNames]. They will be loaded into
262+
/// [Post.customFields]
260263
///
261264
/// In case of an error, a [WordPressError] object is thrown.
262265
Future<List<Post>> fetchPosts({
@@ -271,6 +274,7 @@ class WordPress {
271274
bool fetchAttachments = false,
272275
String postType = "posts",
273276
bool fetchAll = false,
277+
Set<String>? customFieldNames = null
274278
}) async {
275279
if (fetchAll) {
276280
postParams = postParams.copyWith(perPage: 100);
@@ -288,9 +292,16 @@ class WordPress {
288292
List<Post> posts = [];
289293
final list = json.decode(response.body);
290294

291-
for (final post in list) {
295+
for (final Map<String, dynamic> post in list) {
296+
Map<String, dynamic>? customFields;
297+
298+
if (customFieldNames != null && customFieldNames.isNotEmpty) {
299+
customFields = Map.fromEntries(
300+
customFieldNames.map((key) => MapEntry(key, post[key])));
301+
}
302+
292303
posts.add(await _postBuilder(
293-
post: Post.fromJson(post),
304+
post: Post.fromJson(post)..customFields = customFields ?? {},
294305
setAuthor: fetchAuthor,
295306
setComments: fetchComments,
296307
orderComments: orderComments,

lib/schemas/post.dart

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

102+
/// Custom fields on a post.
103+
Map<String, dynamic>? customFields;
104+
102105
Post({
103106
this.date,
104107
this.dateGmt,
@@ -118,6 +121,7 @@ class Post {
118121
this.format = PostFormat.standard,
119122
this.categoryIDs,
120123
this.tagIDs,
124+
this.customFields,
121125
}) : this.title = new Title(rendered: title),
122126
this.featuredMedia = new Media(sourceUrl: featuredMedia),
123127
this.content = new Content(rendered: content),
@@ -204,6 +208,13 @@ class Post {
204208
data['categories'] = listToUrlString(this.categoryIDs ?? []);
205209
data['tags'] = listToUrlString(this.tagIDs ?? []);
206210

211+
if (customFields != null) {
212+
for (final key in customFields!.keys) {
213+
data[key] = customFields![key];
214+
}
215+
}
216+
217+
207218
return data;
208219
}
209220

0 commit comments

Comments
 (0)