Sample code for 30+ languages & platforms
Rust

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 Rust Downloads

Rust

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let http = chilkat::Http::new();

// Use your WordPress login, such as "admin", not the application name.
http.set_login("wp_username");
// Use the application password, such as "Nths RwVH eDJ4 weNZ orMN jabq"
// See WordPress Application Passwords Plugin
http.set_password("app_password");
http.set_basic_auth(true);

// Create the tag "ChatGPT" if it does not already exist.
let json = chilkat::JsonObject::new();
let _ = json.update_string("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.
let resp = chilkat::HttpResponse::new();
if http.http_json("POST", "https://cknotes.com/wp-json/wp/v2/tags", &json, "application/json", &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

let j_resp = chilkat::JsonObject::new();
let _ = j_resp.load(&resp.body_str());

// Check if the tag already exists..
if resp.status_code() == 400 {
    if j_resp.has_member("code") {
        if j_resp.string_of_equals("code", "term_exists", true) {
            // The tag already exists.
            println!("The tag already exists.");
            println!("Tag ID: {}", j_resp.int_of("data.term_id"));
            return;
        }

    }

    // Fall through to check for errors.
}

// Check for errors.
if resp.status_code() != 201 {
    println!("{}", resp.body_str());
    println!("status code = {}", resp.status_code());
    return;
}

// We get here if the tag was created..
println!("The tag was created.");
println!("Tag ID = {}", j_resp.int_of("id"));