Sample code for 30+ languages & platforms
Lua

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

Lua
local chilkat = require("chilkat")

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

local http = chilkat.Http.new()

-- Use your WordPress login, such as "admin", not the application name.
http.login = "wp_username"
-- Use the application password, such as "Nths RwVH eDJ4 weNZ orMN jabq"
-- See WordPress Application Passwords Plugin
http.password = "app_password"
http.basic_auth = true

-- Create the tag "ChatGPT" if it does not already exist.
local json = chilkat.JsonObject.new()
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.
local resp = chilkat.HttpResponse.new()
local success = http:http_json("POST", "https://cknotes.com/wp-json/wp/v2/tags", json, "application/json", resp)
if not success then
    print(http.last_error_text)
    return
end

local jResp = chilkat.JsonObject.new()
jResp:load(resp.body_str)

-- Check if the tag already exists..
if resp.status_code == 400 then
    if jResp:has_member("code") then
        if jResp:string_of_equals("code", "term_exists", true) then
            -- The tag already exists.
            print("The tag already exists.")
            print("Tag ID: " .. jResp:int_of("data.term_id"))
            return
        end
    end

    -- Fall through to check for errors.
end

-- Check for errors.
if resp.status_code ~= 201 then
    print(resp.body_str)
    print("status code = " .. resp.status_code)
    return
end

-- We get here if the tag was created..
print("The tag was created.")
print("Tag ID = " .. jResp:int_of("id"))