Java
Chilkat2 Java
WordPress Create Tag
See more WordPress Examples
Demonstrates how to create a new tag in Wordpress, or to find the ID of an existing tag.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Http http = new Http();
// Use your WordPress login, such as "admin", not the application name.
http.setLogin("wp_username");
// Use the application password, such as "Nths RwVH eDJ4 weNZ orMN jabq"
// See WordPress Application Passwords Plugin
http.setPassword("app_password");
http.setBasicAuth(true);
// Create the tag "ChatGPT" if it does not already exist.
JsonObject json = new JsonObject();
json.updateString("name", "ChatGPT");
// This will create the tag if it does not yet exist.
// If the tag already exists, then a 400 status code is returned.
// If the tag deoes not yet exist, then a 201 status code is returned.
HttpResponse resp = new HttpResponse();
try {
http.httpJson("POST", "https://cknotes.com/wp-json/wp/v2/tags", json, "application/json", resp);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
JsonObject jResp = new JsonObject();
jResp.load(resp.getBodyStr());
// Check if the tag already exists..
if (resp.getStatusCode() == 400) {
if (jResp.hasMember("code")) {
if (jResp.stringOfEquals("code", "term_exists", true)) {
// The tag already exists.
System.out.println("The tag already exists.");
System.out.println("Tag ID: " + jResp.intOf("data.term_id"));
return;
}
}
// Fall through to check for errors.
}
// Check for errors.
if (resp.getStatusCode() != 201) {
System.out.println(resp.getBodyStr());
System.out.println("status code = " + resp.getStatusCode());
return;
}
// We get here if the tag was created..
System.out.println("The tag was created.");
System.out.println("Tag ID = " + jResp.intOf("id"));
}
}