WordPress get_term_by(): Get Category and Post Tag by Slug – WordPress Tutorial

By | September 24, 2020

In this tutorial, we will introduce how to get wordpress category and tag by their slug using get_term_by().

Syntax

get_term_by() is defined as:

get_term_by( string $field, string|int $value, string $taxonomy = '', string $output = OBJECT, string $filter = 'raw' )

$field can be: ‘slug‘, ‘name‘, ‘id‘ or ‘ID‘ (term_id), or ‘term_taxonomy_id‘. It means we can get wordpress category and tag by slug, name and id.

In this tutorial, we will focus on getting category and tag using slug.

How to get category and tag by slug?

Here is an example to get category:

$category = get_term_by('slug', 'term-name', 'category');

$category can be:

(object) array(
   'term_id' => 49,
   'name' => 'Term Name',
   'slug' => 'term-name',
   'term_group' => 0,
   'term_taxonomy_id' => 49,
   'taxonomy' => 'category',
   'description' => '',
   'parent' => 0,
   'count' => 286,
   'filter' => 'raw',
)

In order to get tag, we can do as follows:

$tag = get_term_by('slug', 'java', 'post_tag');

$tag will be a tag with the name of slug ‘java‘.

Leave a Reply

Your email address will not be published. Required fields are marked *