Get Categories And Subcategories In WordPress

,

Get Specific Post Category

The following code will get the category of a specific post. Please note that you have to add this code to either content-single.php or single.php


<?php  $taxonomy = 'category'; 
// ID Gets which assign post 
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
 
// Links seprator.
$separator_link = ', ';
 
if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
 
    $term_ids = implode( ',' , $post_terms );
 
    $terms = wp_list_categories( array(
        'title_li' => '',
        'style'    => 'none',
        'echo'     => false,
        'taxonomy' => $taxonomy,
        'include'  => $term_ids
    ) );
 
    $terms = rtrim( trim( str_replace( '<br />',  $separator_link, $terms ) ), $separator_link );
 
    // show category post.
    echo  $terms;
}  ?>

Get Subcategory From Parent Category

First get the subcategory from the parent category for particular post. Next, add the following code in the post template where the index and archive post loop start. You could also add this code after the title.

<?php
$taxonomy = 'category';

// ID Gets which assign post 
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$post_terms_specific = array (1);
$result_post=array_diff($post_terms, $post_terms_specific);

// Links seprator.
$separator = ', ';

if ( !empty( $result_post ) && !is_wp_error( $result_post ) ) {

 $term_ids = implode( ',' , $result_post);
 $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
 $terms = rtrim( trim( str_replace( '', $separator, $terms ) ), $separator );

 // show category post.
 echo $terms;

}
?>

Name Of Category Get By Id

<?php
//First Method
$id_name= '22';
echo get_the_category_by_ID($id_name);

//Second Method
echo get_cat_name(22);
?>

Description Of Category (Through ID)

Category slug is the URL name of that category:

<?php

 $id_description = '22';
 echo category_description($id_description);

?>

Description Of Category (Get By Slug)

Category slug is the URL name of that category:

<?php

 echo category_description( get_category_by_slug('uncategorized')->term_id ); 

?>

Category Link (Get By ID)

You can generate a link to a particular category using the id. Use the following code:

<?php
 $id_link = '1';
 $categorylink = get_category_link( $id_link );
 echo esc_url($categorylink);
?>




Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.