• Resolved emazero

    (@emazero)


    hi,
    I’ve searched for hours but I can’t find any solution.

    What I’m looking for is how to display categories and subcategories of a selected one.
    here is an example
    Suppose my post is in “subx cat1” I’d like to show as below:

    cat1
    -subx cat1
    -suby cat1
    -subz cat1
    cat2
    cat3
    cat4

    all categories have subones.. but I don’t want to show them all.
    Right now my code is showing all:

    <?php
     $catsy = get_the_category();
    $myCat = $catsy[0]->cat_ID;
    $categories = wp_list_categories('show_count=0&exclude=1&title_li=<h2>MY TITLE</h2>&echo=0&hide_empty=0&'.$currentcategory);
    $category_array = preg_split('/\n/', $categories);
    $count = count($category_array);
    $i = 0;
    while ( $i < $count ) {
            if ( preg_match('/<ul class=(\'|")children(\'|")/i', $category_array[$i+1]) ) {
                    echo preg_replace('/<li class=(\'|")(.+)(\'|")>/i', '<li class=$1parent $2$3>', $category_array[$i]) . "\n";
            } else {
                    echo $category_array[$i] . "\n";
            }
            $i++;
    }
    ?>

    any help?
    thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter emazero

    (@emazero)

    I found a solution here
    (thanks to Andrey)

    but…
    what if a category doesn’t have children categories?
    it gives me back the error
    Invalid argument supplied for foreach() in… functions.php on line…
    Do I needan if statement in that code?
    here is the code

    [Code moderated as per the Forum Rules. Please use the pastebin]

    help please..

    Thread Starter emazero

    (@emazero)

    Michael

    (@alchymyth)

    Do I needan if statement in that code?

    you can try to change each occurrance (line 7 and line 26) of:

    foreach ($categories as $cat)

    to:

    if($categories) foreach ($categories as $cat)
    Thread Starter emazero

    (@emazero)

    it works!
    thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘show subcategories only of a selected parent category’ is closed to new replies.