get_term_by()

This WordPress function requires the CPT-onomy class.

You have been redirected from rachelcarden.com to my new home at WP Dreamer! I moved all my content over so you should be able to find everything you're looking for. If not, please let me know!

Description

Get all CPT-onomy term data from database by term field and data.

Usage

 $cpt_onomy->get_term_by( string $field, string|int $value, string $cpt_onomy, string $output, string $filter );

Parameters

$field (string) (required)
Default: 'id'
Either 'slug', 'name', or 'id'.

$value (string|integer) (required)
Default: none
Search for this term value.

$cpt_onomy (string) (required)
Default: none
Name of the CPT-onomy that the term belongs to.

$output (string) (optional)
Default: OBJECT
Constant OBJECT, ARRAY_A, or ARRAY_N.

$filter (string) (optional)
Default: 'raw'
Default is raw or no WordPress defined filter will be applied.

Return Values

(mixed) Returns term row from database. Will return false if $cpt_onomy does not exist or $term was not found

Term object fields:

  • term_id
  • name
  • slug
  • term_group
  • term_taxonomy_id
  • taxonomy
  • description
  • parent
  • count

Examples

Get term data by the term's name:

global $cpt_onomy;
<?php $term = $cpt_onomy->get_term_by( 'name', 'Tom Hanks', 'actors' ); ?>

Get term data by the term's slug:

global $cpt_onomy;
<?php $term = $cpt_onomy->get_term_by( 'slug', 'tom-hanks', 'actors' ); ?>

Related Functions

, , , ,

WordPress Codex

For more information, refer to the WordPress codex.

  • SMM

    Hi Rachel – I’m trying to exclude categories by slug in the sidebar categories widget. I have code that works, but only for one slug. I want to exclude multiple slugs at the same time. I am using get_term_by, but I don’t know how to get multiple slug names and set them as the $cat variable. I’ve posted this in the WordPress support forum but I’m running out of time and need a really quick reply if you happen to know. :)

    function exclude_widget_categories($args){

    $cat = get_term_by( 'slug', 'featured', 'category' ) ;

    $exclude = $cat->term_id;

    $args["exclude"] = $exclude;

    return $args;

    }

    add_filter("widget_categories_args","exclude_widget_categories");

    • rachelcarden

      In order to exclude multiple terms, define your exclude as a string of comma-separated term IDs. So it would be something like $args[ 'exclude' ] = ’10,20,21,30′;

      • SMM

        Hi Rachel,

        Thank you so much for the reply! However, I really am looking for exclusion by slug so it’s more portable between development and production – I work locally on a Mac and then upload it to the host, and the database on my local machine is never a clone of the one online.

        Anyway, I might have this figured out! Fingers crossed.

        Best,
        SMM