• Hi all, just having a weird issue with get_the_category()

    Maybe I’m not reading things right, but this should be able to retrieve the category to which a specific post belongs correct?

    What I need to do is determine what the super parent to a post is. For example I have a post inside of Therapy, which inside of Procedures. So the structure is like this

    Procedures -> Therapy -> the post

    Procedures has a header graphic and has 4 different sub categories, so I want to display the correct header graphic no matter which post is being looked at.

    I am using get_the_category() but its returning something weird.

    $category = get_the_category();
    		echo $category[0]->name;

    If I do this, the echo returns “Practices” which is a completely different parent category. It has nothing to do with the post. I’m sure I’ve just made a simple error somewhere, but it does seem a little strange…

    any help greatly appreciated!

    Thanks.

Viewing 12 replies - 1 through 12 (of 12 total)
  • Don’t know if it’s the easiest way but found this in my notes:

    <?php
    //display parent categories for each category on a post--must be used in the loop
    $cats = get_the_category();
    if ($cats) {
      foreach($cats as $cat) {
        $parents = array();
        $have_parents = false;
        $parent_id = $cat->category_parent;
        while (0 != $parent_id) {
          $parents[]=$parent_id;
          $next_ancestor = get_category( $parent_id );
          $parent_id = $next_ancestor->category_parent;
        }
        if ($parents) {
          echo 'parents';
          foreach ($parents as $parent) {
            $category = get_term_by('ID',$parent, 'category');
            echo '<p><a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a><p> ';
          }  //foreach ($parents
        }
      } //foreach ($cats
    }
    ?>

    Thread Starter creativelifeform

    (@creativelifeform)

    Hi MichaelH, thanks for the response.

    Unfortunately, I need to get the category of a post within the single.php file, outside of the loop.

    Also I simply can’t understand the logic behind my code returning Practices, that category has nothing to do with the post, so why would that get returned in any instance?

    Thread Starter creativelifeform

    (@creativelifeform)

    Ah!

    Okay I think I’ve sorted out my problem. Here is the new code I am using. Check it out and let me know what you think

    <?php
    		$category = get_the_category();
    		if(count($category) >=2)
    		{
    			$parent = get_cat_name($category[0]->parent);
    		}
    		else
    		{
    			$parent = $category[0]->name;
    		}
    
    		echo $parent;
    	  ?>

    Thread Starter creativelifeform

    (@creativelifeform)

    Okay a slight refinement and a weird nuance. First the refinement:

    <?php
    		$category = get_the_category();
    		if(count($category) >=1)
    		{
    			$parent = get_cat_name($category[0]->parent);
    		}
    		else
    		{
    			$parent = $category[0]->name;
    		}
    
    		echo $parent;
    	  ?>

    Now, the nuance. I have a category; Procedures, and a sub category, Regenerative Procedures. So the structure is like

    Procedures -> Regenerative Procedures.

    For some reason this was the only category where this code was not working. I figured out that this was due to the fact that alphabetically, Regenerative comes after Procedures, because all the other sub categories start with letters before “P”. Is WordPress really organizing these based on ABC? A bit strange…

    CodePoet

    (@design_dolphin)

    This works for me. YMMV.

    <?php
    
    	foreach (get_the_category() as $cat) {
    
    		$parent = get_category($cat->category_parent);
    		$parent_name = $parent->cat_name;
    		$parent_url =  $parent->slug;
    
    	}
    
    	?>
    
    <a rel="nofollow"  title="<?php echo $parent_name; ?>" href="<?php  echo get_option('home'); ?>/<?php  echo $parent_url; ?>"><?php echo $parent_name; ?></a>

    If you just want the name of the parent category it is

    $parent_name

    You can then also remove $parent_url = $parent->slug; from the code snippet.

    Thread Starter creativelifeform

    (@creativelifeform)

    Hi design_dolphin, thanks for the reply.

    Are you placing this code in the template file? If I use this and echo $parent_name, nothing happens.

    My code works fine except for 2 instances. The first is if the sub category’s name is placed before the parent category’s alphabetically, the second is within the actual post, for some reason a completely random category, unrelated to any of the posts is being returned.

    Can’t really understand why this is happening…

    CodePoet

    (@design_dolphin)

    AFAIK it should work in template files sidebar.php (index.php, category.php, and single.php) and single.php, both inside and outside of the loop.

    Might be time in this case to do some debugging on your WordPress install, but I am not sure. It could be that there are circumstances that the code does not work. Make sure to backup everything before you do any of the following.

    What happens if you empty the single.php and try to find the parent category?
    Does the code work when placed in the ‘default’ theme?
    Do you or have you installed any plugins?
    Have you made any changes to the core?
    Have you written any custom code?

    I’m not aware of any bugs with categories, that is not to say there are none. or maybe this is because of something in the name or slug of the category created. Also you could try do a clean install with WordPress and the ‘default’ theme. Add a simple parent category like ‘fruit’ and give that a few children like ‘apple’, ‘banana’, and ‘pear’. And then run the known codes.

    Thread Starter creativelifeform

    (@creativelifeform)

    Hey, I’ve actually just resolved to do it with Javascript for now. Very easy that way. Its really just graphics, not too fussed if someone browsing with Javascript turned off doesn’t see the correct header graphic, I don’t really know who does that these days anyway.

    CodePoet

    (@design_dolphin)

    You could also set a variable with PHP in a theme template.

    So:

    <?php
    
    	if (in_category('your parent category name') ||  post_is_in_descendant_category( your parent category id )) {
    
    		$background_image_1 = echo "<img class=\"background_image\" src=\"background.jpg\" alt=\"my alt text\" />";
    
    	}
    
    	?>

    It would solve the dependency on Javascript. You could probably write a plugin, if one doesn’t exist already, to change the image per category in the admin panel.

    See also Function Reference/in category

    Still worrysome though that you can’t get the parent category, to tell you the truth.

    Edit: Haven’t tested that code, but you get the gist.

    Thread Starter creativelifeform

    (@creativelifeform)

    Yeah, I don’t know. It works with Javascript, I’m not too bothered to depend on Javascript, its really just a visual element and nothing related to key functionality.

    Thread Starter creativelifeform

    (@creativelifeform)

    Okay, now this is really frustrating. I’m cool with using javascript for the above issue, but now I want to do something really simple and its not going to work because of this problem.

    Just to recap; I’m inside of a category called Procedures. I am using the following code:

    $category = get_the_category();
    echo $category[0]->name

    The echo is happening inside of a loop:

    <?php $my_query = new WP_Query('category_name=Procedures'); ?>
    <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>

    And it is returning “Practices”

    I just don’t know how this is possible…The posts inside this category have nothing to do with Practices, they are all children of the Procedures category.

    Thread Starter creativelifeform

    (@creativelifeform)

    Update: weirdly enough, if I use <?php the_category(‘, ‘) ?> it writes them out fine BUT they are in alphabetical order. Is there any way to use the_category() and just have it order via parent->child?

Viewing 12 replies - 1 through 12 (of 12 total)
  • The topic ‘get_the_category question’ is closed to new replies.