Search
Close this search box.

Get child of parent categories in wordpress

Amitpal Singh
Amitpal Singh
October 9, 2022

Get child of parent categories in wordpress rest api and json method:

Paste below code in functions.php

/* get sub categories */
add_action( 'rest_api_init', function () {
    register_rest_route( 'yourgoodname', '/subcategories/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_sub_category_func',
    ) );
} ); 

function my_sub_category_func( $data ) {
 	$useableid = $data['id'];
    $parent = $data->get_param( 'parent' );
	
	sub_category_menu($parent);

}


function sub_category_menu($parentcatslug){
	$category = get_category_by_slug( $parentcatslug );
		$args = array(
		'type'                     => 'store',
		'child_of'                 => $category->term_id,
		'orderby'					=> 'ID',
		'order'                    => 'ASC',
		'hide_empty'               => FALSE,
		'hierarchical'             => 1,
		'taxonomy'                 => 'category',
		); 
		$child_categories = get_categories($args );

		$category_list = array();
	
		if ( !empty ( $child_categories ) ){
			foreach ( $child_categories as $child_category ){
				$category_list[] = array('slug' => $child_category->slug, 'name' => $child_category->name, 'id' => $child_category->term_id);				
			}
		}
	echo json_encode($category_list);
	
} 
Fetch using this url below (don’t forget to change domain name to your site name)
https://domain.com/wp-json/yourgoodname/subcategories/1?parent=parent_category_slug 

Share this post:

How to Attribute?

Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
for Example: Website, Social Media, Blogs, ebooks , newsletter, etc.
Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
Copied!

Got a Question? Check out our FAQ Section.

Your action, our appreciation

It encourage us to give you more valuable content on website.