Get only parent categories wordpress

Picture of Amitpal Singh
Amitpal Singh
October 9, 2022
Get only parent categories wordpress rest api and json method:

Paste below code in functions.php

/* parent categories via rest api */
add_action( 'rest_api_init', function () {
    register_rest_route( 'yourgoodname', '/parentonly/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_parent_category_func',
    ) );
} ); 

function my_parent_category_func( $data ) {
 	$useableid = $data['id'];
 	
 	/* below is the main code to use just as it is anywhere or functions.php*/
	$args = array(
  'type' => 'store',
  'orderby' => 'name',
  'order' => 'ASC',
  'parent' => 0
	);
$parent_categories = get_categories($args);
	
			$category_list = array();
	
		if ( !empty ( $parent_categories ) ){
			foreach ( $parent_categories as $parent_category ){
				$category_list[] = array('slug' => $parent_category->slug, 'name' => $parent_category->name, 'id' => $parent_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/parentonly/1/ 

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.