Calling WordPress REST APIs to create users, articles, posts, etc. with examples using JAVA
Wordpress has an amazing REST API that lets you do pretty much anything that you would need. You can add users, add articles, create tags, create categories etc.
My backend system is in JAVA and here is how you can do various things in WordPress using JAVA:
For this we are going to use this really good package: https://github.com/Afrozaar/wp-api-v2-client-java
<dependency>
<groupId>com.afrozaar.wordpress</groupId>
<artifactId>wp-api-v2-client-java</artifactId>
<version>4.8.3</version>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
<exclusion>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
</exclusion>
</exclusions>
</dependency>
P.S. I have removed some logging dependencies as they made the jar too big and it was also adding a lot of debug logs that we really don’t need.
Creating the Wordpress Client
Wordpress getWordpressClient() {
String baseUrl = "wp-url/wp-json/";
String username = "admin-email";
String password = "admin-password";
return ClientFactory
.fromConfig(ClientConfig.of(baseUrl, username, password,
false,
true));
}
Creating a Tag
Term term = new Term();
term.setName("tag1);
term = wordpress.createTag(term);
Creating a Category
Term term = new Term();
term.setName(category);
term.setSlug(category);
Term cat = wordpress.createCategory(term);
The response object will fail if the slug already exists, so its a good idea to wrap this in a try-catch statement.
Creating a Post/Article
Post post = PostBuilder.aPost().build();
post.setTitle(TitleBuilder.aTitle().withRendered("title).build());
post.setExcerpt(ExcerptBuilder.anExcerpt().withRendered("description").build());
post.setContent(ContentBuilder.aContent().withRendered("summary").build());
post.setDate(Instant.now().toString());
post.setSlug("test-article");
post.setAuthor(authorId);
//Add IDs of tags that you want to add
post.setTagIds(tags);
//Add IDs of categories that you want to add
post.setCategoryIds(categoryIds);
createdPost = wordpress.createPost(post, PostStatus.publish);
Creating a User
User user = new User();
user.setEmail("test@testuser.com");
user.setName("Name");
user.setSlug("test");
user.setNickname(name);
AvatarUrls avatarUrls = new AvatarUrls();
avatarUrls.set96("user-image-url");
avatarUrls.set48("user-image-url");
avatarUrls.set24("user-image-url");
user.setAvatarUrls(avatarUrls);
try {
user = wordpress.createUser(user, name, Utils.getAlphaNumericString(20));
} catch (UsernameAlreadyExistsException e) {
log.error(e);
} catch (UserEmailAlreadyExistsException e) {
log.error(e);
}Media media = new Media();
media.setCaption("caption");
media.setDescription("description");
media.setAltText("alt-text");
Resource resource;
//Load images from a URL, save them local(/tmp) and then upload to
// wordpress
BufferedImage image;
try {
String imagePath = Utils.read("urlToImage");
File targetFile = new File(imagePath);
//Only upload image if size is less than 4MB
if ((double) targetFile.length() / (1024 * 1024) < 4.0))) {
resource = new FileSystemResource(targetFile);
media1 = wordpress.createMedia(media, resource);
}
} catch (Exception e) {
log.error(e);
}
Uploading a Media/Image
Media media = new Media();
media.setCaption("caption");
media.setDescription("description");
media.setAltText("alt-text");
Resource resource;//Load images from a URL, save them local(/tmp) and then upload to
// wordpressBufferedImage image;
try {
String imagePath = Utils.read("urlToImage");
File targetFile = new File(imagePath);
//Only upload image if size is less than 4MB
if ((double) targetFile.length() / (1024 * 1024) < 4.0))) {
resource = new FileSystemResource(targetFile);
media1 = wordpress.createMedia(media, resource);
}
} catch (Exception e) {
log.error(e);
}
After creating a “featured image”, WordPress will not make the image available for few seconds to a few minutes. Hence you can’t just add that features image to a post. We overcame this by directly adding an entry into the mysql database.
This is the code to add a featured Image
public void setFeaturedImage(Post post, Media media) {
String sqlQuery = "INSERT INTO `wp_postmeta` (`meta_id`, `post_id`, `meta_key`, `meta_value`) "
+ "VALUES (NULL, "
+ "'" + post.getId() + "', "
+ "'_thumbnail_id', "
+ "'" + media.getId() + "')";
log.info(sqlQuery);
runSqlQuery(sqlQuery);
}
Hope you guys find this helpful. Let me know if you find any errors in the code.
Originally published at https://system.camp on July 16, 2020.