Zig
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const http = try chilkat.Http.init();
defer http.deinit();
// 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.
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.updateString("name", "ChatGPT") catch {};
// 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.
const resp = try chilkat.HttpResponse.init();
defer resp.deinit();
http.httpJson("POST", "https://cknotes.com/wp-json/wp/v2/tags", json, "application/json", resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
const j_resp = try chilkat.JsonObject.init();
defer j_resp.deinit();
j_resp.load(try resp.getBodyStr(alloc)) catch {};
// Check if the tag already exists..
if (resp.getStatusCode() == 400) {
if (j_resp.hasMember("code")) {
if (j_resp.stringOfEquals("code", "term_exists", true)) {
// The tag already exists.
std.debug.print("The tag already exists.\n", .{});
std.debug.print("Tag ID: {d}\n", .{j_resp.intOf("data.term_id")});
return;
}
}
// Fall through to check for errors.
}
// Check for errors.
if (resp.getStatusCode() != 201) {
std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});
std.debug.print("status code = {d}\n", .{resp.getStatusCode()});
return;
}
// We get here if the tag was created..
std.debug.print("The tag was created.\n", .{});
std.debug.print("Tag ID = {d}\n", .{j_resp.intOf("id")});
}