Grow your CSS skills. Land your dream job.

How to make a multi-peer PHP array based on WP cat heirachy?

  • # November 12, 2009 at 10:25 am

    Does anyone know how to make a multi-peer PHP array based on WP category heirachy

    I need to make a custom nav bar based on categories.

    For example:

    Code:
    array->
    4->0
    5->0
    8->array->
    9->0
    6->array->
    1->0
    3->array->
    10->0
    2->0
    3->0

    Where the key would be the cat_ID and the value would be either 0, if it has no children, or an array of it’s children and so on.
    Does this make sense?

    Thanks :D

    # November 15, 2009 at 8:13 am

    You can use a custom walker to achieve this. It’s a fairly advanced topic but i’ll "walk" you through it :roll:

    Start by creating a class for your walker either in functions.php in your theme, or wherever you like. You can use this as a template.

    Code:
    class CategoryNavigationWalker extends Walker {
    var $db_fields = array(‘parent’ => ‘parent’, ‘id’ => ‘term_id’);

    function start_lvl(&$output, $depth) {
    $output .= “

      n”;
      }

      function end_lvl(&$output, $depth) {
      $output .= “

    n”;
    }

    function start_el(&$output, $category, $depth, $args = null) {
    $output .= “

  • {$category->name}”;
    }

    function end_el(&$output, $category, $depth, $args = null) {
    $output .= “

  • “;
    }
    }

This example creates an unordered list, but you can change it to accommodate ordered lists, divs, drop down menus, whatever you fancy. I have just listed the categories but for a navigation you will obviously need to include hyperlinks.

Next a function that uses the walker to produce the navigation menu.

Code:
function category_navigation() {
$walker = new CategoryNavigationWalker();
echo $walker->walk(get_categories(), 0);
}

Finally, when you want to produce the navigation menu in your template use:

Code:
    < ?php category_navigation(); ?>

Hope that is easy to understand and solves your problem.

Dave

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".