megclaypool of Rootid
11/28/2018 - 10:45 PM

Useful WordPress Taxonomy Functions

get_the_category( int $id = false )

Retrieve post categories, but only for the default taxonomy. If you're using it inside a post, the post ID is not necessary.

Example:

$temp = get_the_category( $post->ID );
var_dump($temp);

Output:

array (size=1)
  0 => 
    object(WP_Term)[1438]
      public 'term_id' => int 1
      public 'name' => string 'Uncategorized' (length=13)
      public 'slug' => string 'uncategorized' (length=13)
      public 'term_group' => int 0
      public 'term_taxonomy_id' => int 1
      public 'taxonomy' => string 'category' (length=8)
      public 'description' => string '' (length=0)
      public 'parent' => int 0
      public 'count' => int 2
      public 'filter' => string 'raw' (length=3)
      public 'cat_ID' => int 1
      public 'category_count' => int 2
      public 'category_description' => string '' (length=0)
      public 'cat_name' => string 'Uncategorized' (length=13)
      public 'category_nicename' => string 'uncategorized' (length=13)
      public 'category_parent' => int 0

get_the_terms( int|object $post, string $taxonomy )

Retrieve post categories for any taxonomy. Generates an array of arrays with information on each term in the selected taxonomy for that post.

Example:

$temp = get_the_terms( $post->ID, 'threats' );
var_dump($temp);

Output:

array (size=2)
  0 => 
    object(WP_Term)[1438]
      public 'term_id' => int 11
      public 'name' => string 'Digital' (length=7)
      public 'slug' => string 'digital' (length=7)
      public 'term_group' => int 0
      public 'term_taxonomy_id' => int 11
      public 'taxonomy' => string 'threats' (length=7)
      public 'description' => string '' (length=0)
      public 'parent' => int 0
      public 'count' => int 2
      public 'filter' => string 'raw' (length=3)
  1 => 
    object(WP_Term)[1364]
      public 'term_id' => int 12
      public 'name' => string 'Financial' (length=9)
      public 'slug' => string 'financial' (length=9)
      public 'term_group' => int 0
      public 'term_taxonomy_id' => int 12
      public 'taxonomy' => string 'threats' (length=7)
      public 'description' => string '' (length=0)
      public 'parent' => int 0
      public 'count' => int 1
      public 'filter' => string 'raw' (length=3)

get_the_term_list( int $id, string $taxonomy, string $before = '', string $sep = '', string $after = '' )

Retrieve a post’s terms as an html encoded list of links with specified separators.

Example:

$temp = get_the_term_list( $post->ID, 'threats', '', ', ', '' );
var_dump($temp);

Output:

/Sites/eri/wp-content/themes/radicati-eri/single.php:71:string '<a href="http://eri.test/?taxonomy=threats&#038;term=digital" rel="tag">Digital</a>, <a href="http://eri.test/?taxonomy=threats&#038;term=financial" rel="tag">Financial</a>' (length=172)