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

In WordPress categories can be organizate in a structure "father", "son". This means that a single post can belong to multiple categories. 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 ) { function get_parent_category ($ 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 to: " "

  1. March 21, 2009 luca:

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

  2. March 22, 2009 Giovan Battista Fazioli :

    @ Luca:

    you can create multiple parent categories and assign each child categories with the same name?

    Currently WordPress does not allow this. Although it is possible to decide the father, and then at the logical level to avoid confusing the two categories are identical (in terms of name), WordPress prevent the use of that 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 "2 Father." You create a first "Child 1" and is associated as a father, "Father 1". It then creates "Child A" and associating it with "Father 2". Once this is done you go to change the name of "Son A" in "Child 1", although the "slug" (short) remains "son-in". At this point we have:

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

Leave a comment

TAG XHTML PERMITS: CODE ENTRY:
 <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