get all sub categories without specify any category

I have 2 levels of categories ( one sub-category only. No sub-sub category ). I need to get all sub categories without parent category. (I don’t want to specify any parent category.)

Example:

Read More
p_cat1
   s_cat1
   s_cat2
p_cat4
p_cat3
   s_cat4
   s_cat5
   s_cat7

from here, I need

s_cat1
s_cat2
s_cat4
s_cat5
s_cat7

And, I need there to be a URL for each of those sub-categories. I want to give <a> for each subcategory.

How do I do that?

Related posts

Leave a Reply

3 comments

  1. You could use get_categories().

    Returns an array of category objects matching the query parameters.

    Arguments are pretty much the same as wp_list_categories and can be passed as either array or in query syntax.

    // Fetch parent categories
    $parent_categories = get_categories( 'parent=0' );
    
    foreach ( $parent_categories as $parent_category ) {
      // Fetch child categories
      $args = array(
        'parent' => $parent_category->term_id
      );
    
      $categories = get_categories( $args );
    
      foreach ( $categories as $category ) {
        printf( '<div>%s</div>', $category->name );
      }
    }
    

    This is a very simple example of the code without extra parameters like hide_empty, type etc.

  2. The get_categories function of WordPress returns all the categories, you can loop over the list of categories returned by get_categories and check for the parent property, if parent is ‘0’ then its the parent category other wise it is the sub category.

    function get_sub_categories() {
        $cats = get_categories();
        $subcats = array();
        foreach( $cats as $cat ) {
            if ($cat->parent != '0') {
                $subcats[] = $cat;
            }
        }
        return $subcats;
    }
    

    I don’t know how you want with URL but you can try the following function which will only return Sub categories name hyper linked to their category URLs

    function get_sub_categories() {
        $cats = get_categories();
        $subcats = array();
        foreach( $cats as $cat ) {
            if ($cat->parent != '0') {
                $subcats[] = '<a href="' . get_category_link( $cat->term_id ) .'">' . $cat->name . '</a>';
            }
        }
        return $subcats;
    }
    
  3. function kill_childcat_postlink($link) {
        $result = $link;
        $bloghome = get_bloginfo( 'home' );
        if (preg_match('%' . $bloghome . '/(.*?)/(.*?)/(.*?)/$%i', $link))
            $result = preg_replace('%' . $bloghome . '/(.*?)/.*?/(.*?)/$%i', $bloghome . '/$1/$2/', $link);     
        return $result;
    }
    add_filter('post_link','kill_childcat_postlink');