Very short snippet: how to retrieve the parent category in Wordpress

In WordPress categories can be arranged in a structure "father" "son". This means that a single post can belong to multiple categories. It may be useful in some cases determine, regardless of the "children", which is the parent category of a post:

1
2
3
4
5
6
7
8
9
10
11
/ **
* Returns the parent category of a post
*
* @ Return
* @ Param object $ post_id
* /
$post_id ) { get_parent_category function ($ post_id) {
wp_get_object_terms ( $post_id , 'category' , array ( 'fields' => 'all' ) ) ; $ Cats = wp_get_object_terms ($ post_id, 'category', array ('fields' => 'all'));
$cats as $key => $cat ) if ( $cat -> parent == 0 ) return $cat ; foreach ($ cats as $ key => $ cat) if ($ cat -> parent == 0) return $ cat;
; return null;
}

2 comments: "Very short snippet: how to retrieve the parent category in WordPress"

  1. March 21, 2009 luca:

    thanks for the tip, and congratulations on the blog full of interesting content. I wanted to ask a question about parent and child categories: You can create multiple parent categories, and assign categories to each child with the same name?

  2. March 22, 2009 Giovambattista Fazioli :

    @ Luca:

    You can create multiple parent categories, and assign categories to each child with the same name?

    WordPress does not currently allow it. Although you can decide the father, and then at the logical level to avoid confusing the two categories are identical (in terms of name), WordPress will prevent use of the same name for a category, even if it belongs to different fathers.
    However, it is possible to partially circumvent the obstacle with a small artefizio: you create two fathers "Father 1" and "Father 2." It first creates a "Child 1" and joins his father as "Father 1". It then creates "A Son" and is associated with "Father 2." Without this you go to change the name of "Son A", "Child 1", even though the "slug" (short) is a "son-in". At this point we have:

    Padre 1 ->Figlio 1 
    Padre 2 -> Figlio 1

Leave a comment

XHTML TAG PERMIT: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL