Development & EngineeringFeb 06, 2022
Create, Update, Delete, and Edit WordPress Terms with PHP.
Terms can be created, queried, and edited using PHP. WordPress provides functions for this purpose.
Querying a WordPress Term with PHP
To query a term, you can use the function get_term($term_id, $taxonomy). You only need the ID and the taxonomy.
$term_id = 10;
$taxonomy = "post_tag";
/**
* @var \WP_Term $Term
*/
$Term = get_term($term_id, $taxonomy);
Querying a WordPress Term by Slug, Name, or Term ID
You can also query a term by slug, name, or ID using get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw').
/**
* Query WordPress Term by Slug
* @var \WP_Term|array|false $Term
*/
$Term = get_term_by("slug", "i-am-a-slug", "post_tag");
/**
* Query WordPress Term by Name
* @var \WP_Term|array|false $Term
*/
$Term = get_term_by("name", "I am a Slug", "post_tag");
/**
* Query WordPress Term by Term ID
* @var \WP_Term|array|false $Term
*/
$Term = get_term_by("term_id", 10, "post_tag");
Querying All WordPress Terms from a Taxonomy
Using get_terms($args), you can query all terms of a taxonomy.
$args = array(
'taxonomy' => 'post_tag',
'hide_empty' => false
);
/**
* @var array<\WP_Term> $Terms
*/
$Terms = get_terms($args);
Inserting a New WordPress Term into a Taxonomy
New terms can be added using wp_insert_term($term, $taxonomy, $args = array()). If the term already exists, it will be updated.
/**
* Arguments can be specified optionally
*/
$args = array(
'description' => 'Description',
'parent' => 0,
'slug' => ''
);
/**
* Create a new term in the post_tag taxonomy
*/
$term_id = wp_insert_term('I am a new term', 'post_tag', $args);
Deleting a Term in WordPress via PHP
Terms can also be quickly and easily removed via PHP. The function wp_delete_term($term_id,$taxonomy) exists for this purpose.
/**
* Deletes the term with Term ID 10 in the post_tag taxonomy
*/
$result = wp_delete_term(10, 'post_tag');
Querying Metadata of a Term
Terms can also contain metadata like posts. This can be queried using get_term_meta($term_id, $meta_key, $single).
/**
* Returns a single value
* @var string|int|mixed $my_meta_data
*/
$my_meta_data = get_term_meta(10,'my_meta_data', true);
/**
* Returns an array
* @var array $my_meta_data
*/
$my_meta_data = get_term_meta(10,'my_meta_data');
Deleting Metadata of a Term in WordPress
Metadata of terms can be deleted in WordPress using delete_term_meta($term_id, $meta_key, $meta_value = '').
$result = delete_term_meta(10, 'my_meta_data');
Updating/Creating Metadata of a Term via PHP
To update existing metadata of a term, the function update_term_meta($term_id, $meta_key, $meta_value, $prev_value = '') is used. If the data does not yet exist, it will be created.
$result = update_term_meta(10, 'my_meta_data', 'this will be output');