WordPress API: insert a new tag / get a tag


CURL:

base64credentials="VVNFUjpQQVNTV09SRA=="
curl -sk --request POST --url http://tutorialspots.com/wp-json/wp/v2/tags --header "authorization: Basic $base64credentials" --header "content-type: application/json" -d '{"name":"test"}'

Result for insert a new tag:

{"id":1602,"count":0,"description":"","link":"http:\/\/tutorialspots.com\/tag\/test\/","name":"test","slug":"test","taxonomy":"post_tag","meta":[],"_links":{"self":[{"href":"http:\/\/tutorialspots.com\/wp-json\/wp\/v2\/tags\/1602"}],"collection":[{"href":"http:\/\/tutorialspots.com\/wp-json\/wp\/v2\/tags"}],"about":[{"href":"http:\/\/tutorialspots.com\/wp-json\/wp\/v2\/taxonomies\/post_tag"}],"wp:post_type":[{"href":"http:\/\/tutorialspots.com\/wp-json\/wp\/v2\/posts?tags=1602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}

Result for get a tag by name:

{"code":"term_exists","message":"A term with the name provided already exists in this taxonomy.","data":{"status":400,"term_id":1602}}

PHP:

<?php

function grabAPI($url,$method='POST',$data='')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);     
    curl_setopt($ch, CURLOPT_TIMEOUT,30);     
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $uaa = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'; 
    curl_setopt($ch, CURLOPT_USERAGENT, $uaa);
    $header = array(
        'authorization: Basic VVNFUjpQQVNTV09SRA==',
        'content-type: application/json',
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method);
    if($data)
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    
    return curl_exec($ch);
}
 
$x = grabAPI('http://tutorialspots.com/wp-json/wp/v2/tags','POST','{"name":"test"}');
$x = json_decode($x);
$x = empty($x->data->term_id)?$x->id:$x->data->term_id;
echo $x;

Leave a Reply