Forums

display child category name and link to cat page (3 posts)

  1. trixienolix
    Member
    Posted 2 weeks ago #

    hi
    i have a site with say 3 categories, two are children of the other
    e.g.
    fruit (id 3)
    -- apples (id 4)
    -- pears (id 6)

    For all posts within the category "apples" I want to display the word "apples" and a link to that category page.

    I need some code that says something like "for parent category 3 display the name of it's children and the relevant link".

    I've looked at various functions but none seem to do this? Maybe the nearest is "get_the_category" but I'm unsure how to code it exactly.

    Any help gratefully received

  2. trixienolix
    Member
    Posted 2 weeks ago #

    ok i've found this thread http://wordpress.org/support/topic/140469?replies=29 and this code ALMOST does what I want:

    <?php
    /*
    
    */
    //exclude these from displaying
    $exclude = array("Project", "London", "News");
    
    //set up an empty categorystring
    $catagorystring = '';
    
    //loop through the categories for this post
    foreach((get_the_category()) as $category)
    {
    	//if not in the exclude array
    	if (!in_array($category->cat_name, $exclude))
    	{
    		//add category with link to categorystring
    		$catagorystring .= '<a href="'.get_bloginfo(url).get_option('category_base').'/'.$category->slug.'">'.$category->name.'</a>, ';
    	}
    }
    
    //strip off last comma (and space) and display
    echo substr($catagorystring, 0, strrpos($catagorystring, ','));
    
    ?>

    All i need is for the $exclude to be an $include and for the code to say something like "include child of fruit" rather than excluding specific categories.

    Can anyone help?

  3. phatcheesefish
    Member
    Posted 1 week ago #

    Here you go - does exactly what you want

    //set up an empty categorystring
    $catagorystring = '';
    
    // get all categories
    foreach(get_the_category() as $category) {
    	// if category parent is 3 (fruit) then add this category to the string
    	if ($category->category_parent == 3) {
    		$catagorystring .= '<a href="'.get_bloginfo('url') . "/category" . '/' . $category->slug . '">' . $category->name . '</a>, ';
    	}
    }
    
    //strip off last comma (and space)
    echo substr($catagorystring, 0, strrpos($catagorystring, ','));

Reply

You must log in to post.

About this Topic

Tags