{"id":11,"date":"2020-07-16T14:48:39","date_gmt":"2020-07-16T14:48:39","guid":{"rendered":"https:\/\/system.camp\/index.php\/2020\/07\/16\/adding-users-articles-to-wordpress-using-java\/"},"modified":"2020-10-06T07:26:51","modified_gmt":"2020-10-06T07:26:51","slug":"adding-users-articles-to-wordpress-using-java","status":"publish","type":"post","link":"https:\/\/system.camp\/tutorial\/adding-users-articles-to-wordpress-using-java\/","title":{"rendered":"Calling WordPress REST APIs to create users, articles, posts, etc. with examples using JAVA"},"content":{"rendered":"\n

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.<\/p>\n\n\n\n

My backend system is in JAVA and here is how you can do various things in WordPress using JAVA:<\/p>\n\n\n\n

For this we are going to use this really good package: https:\/\/github.com\/Afrozaar\/wp-api-v2-client-java<\/a><\/p>\n\n\n\n

<dependency>  <groupId>com.afrozaar.wordpress<\/groupId>\n  <artifactId>wp-api-v2-client-java<\/artifactId>\n  <version>4.8.3<\/version>\n  <exclusions>\n    <exclusion>\n      <groupId>ch.qos.logback<\/groupId>\n      <artifactId>logback-classic<\/artifactId>\n    <\/exclusion>\n    <exclusion>\n      <groupId>commons-beanutils<\/groupId>\n      <artifactId>commons-beanutils-core<\/artifactId>\n    <\/exclusion>\n    <exclusion>\n      <groupId>com.fasterxml.jackson.jaxrs<\/groupId>\n      <artifactId>jackson-jaxrs-json-provider<\/artifactId>\n    <\/exclusion>\n  <\/exclusions>\n<\/dependency><\/code><\/pre>\n\n\n\n

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.<\/p>\n\n\n\n

Creating the WordPress Client<\/h2>\n\n\n\n
WordPress getWordpressClient() {\n    String baseUrl = \"wp-url\/wp-json\/\";\n    String username = \"admin-email\";\n    String password = \"admin-password\";\n    return ClientFactory\n      .fromConfig(ClientConfig.of(baseUrl, username, password,\n          false,\n          true));\n}<\/code><\/pre>\n\n\n\n

Creating a Tag<\/h2>\n\n\n\n
Term term = new Term();\nterm.setName(\"tag1);\nterm = wordpress.createTag(term);<\/code><\/pre>\n\n\n\n

Creating a Category<\/h2>\n\n\n\n
Term term = new Term();\nterm.setName(category);\nterm.setSlug(category);\nTerm cat = wordpress.createCategory(term);<\/code><\/pre>\n\n\n\n

The response object will fail if the slug already exists, so its a good idea to wrap this in a try-catch statement.<\/p>\n\n\n\n

Creating a Post\/Article<\/h2>\n\n\n\n
Post post = PostBuilder.aPost().build();\npost.setTitle(TitleBuilder.aTitle().withRendered(\"title).build());\npost.setExcerpt(ExcerptBuilder.anExcerpt().withRendered(\"description\").build());\npost.setContent(ContentBuilder.aContent().withRendered(\"summary\").build());\npost.setDate(Instant.now().toString());\npost.setSlug(\"test-article\");\npost.setAuthor(authorId);\n\/\/Add IDs of tags that you want to add\npost.setTagIds(tags);\n\/\/Add IDs of categories that you want to add\npost.setCategoryIds(categoryIds);\ncreatedPost = wordpress.createPost(post, PostStatus.publish);<\/code><\/pre>\n\n\n\n

Creating a User<\/h2>\n\n\n\n
User user = new User();\nuser.setEmail(\"test@testuser.com\");\nuser.setName(\"Name\");\nuser.setSlug(\"test\");\nuser.setNickname(name);\nAvatarUrls avatarUrls = new AvatarUrls();\navatarUrls.set96(\"user-image-url\");\navatarUrls.set48(\"user-image-url\");\navatarUrls.set24(\"user-image-url\");\nuser.setAvatarUrls(avatarUrls);\ntry {\n  user = wordpress.createUser(user, name, Utils.getAlphaNumericString(20));\n} catch (UsernameAlreadyExistsException e) {\n  log.error(e);\n} catch (UserEmailAlreadyExistsException e) {\n  log.error(e);\n}<\/code><\/pre>\n\n\n\n

Uploading a Media\/Image<\/h2>\n\n\n\n
Media media = new Media();\nmedia.setCaption(\"caption\");\nmedia.setDescription(\"description\");\nmedia.setAltText(\"alt-text\");\nResource resource;\n\/\/Load images from a URL, save them local(\/tmp) and then upload to\n\/\/ wordpress\nBufferedImage image;\ntry {\n  String imagePath = Utils.read(\"urlToImage\");\n  File targetFile = new File(imagePath);\n  \/\/Only upload image if size is less than 4MB\n  if ((double) targetFile.length() \/ (1024 * 1024) < 4.0))) {\n    resource = new FileSystemResource(targetFile);\n    media1 = wordpress.createMedia(media, resource);\n  }\n} catch (Exception e) {\n  log.error(e);\n}<\/code><\/pre>\n\n\n\n

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.<\/p>\n\n\n\n

This is the code to add a featured Image:<\/p>\n\n\n\n

public void setFeaturedImage(Post post, Media media) {\n    String sqlQuery = \"INSERT INTO `wp_postmeta` (`meta_id`, `post_id`, `meta_key`, `meta_value`) \"\n        + \"VALUES (NULL, \"\n        + \"'\" + post.getId() + \"', \"\n        + \"'_thumbnail_id', \"\n        + \"'\" + media.getId() + \"')\";\n    log.info(sqlQuery);\n    runSqlQuery(sqlQuery);\n}<\/code><\/pre>\n\n\n\n

Hope you guys find this helpful. Let me know if you find any errors in the code.<\/p>\n","protected":false},"excerpt":{"rendered":"

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.<\/p>\n","protected":false},"author":1,"featured_media":124,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[40,35],"tags":[4,3,2],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts\/11"}],"collection":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/comments?post=11"}],"version-history":[{"count":3,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts\/11\/revisions"}],"predecessor-version":[{"id":127,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts\/11\/revisions\/127"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/media\/124"}],"wp:attachment":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/media?parent=11"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/categories?post=11"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/tags?post=11"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}