Welcome to my unobtrusive blog!
By default I blog in english but there is also german content.

Wordpress: Getting the category via a post id outside the loop

December 10th, 2008 Posted in english

If you want to get the category of a post outside the wordpress loop, you can use the following sql statement to get the category id, its name and its slug:

SELECT term_id AS category_id, name AS category_name, slug AS category_slug 
FROM wp_terms 
WHERE term_id = (SELECT term_taxonomy_id FROM wp_term_relationships WHERE object_id=__POSTID__)

Replace “__POSTID__” with the post’s id.

follow comments via rss
  1. 2 Responses to “Wordpress: Getting the category via a post id outside the loop”

  2. By justfrank on Feb 11, 2009

    That didn’t work for me.

    Here’s what I did to get just the ID. Maybe not the smartest code ever, but it does his job ;)

    $thecatID = $wpdb->get_results(”
    SELECT term_id
    FROM wp_terms
    WHERE term_id = (
    SELECT term_id
    FROM wp_term_taxonomy
    WHERE taxonomy = ‘category’
    AND term_taxonomy_id IN (
    SELECT term_taxonomy_id
    FROM wp_term_relationships
    WHERE object_id=$post->ID)
    )
    “, ARRAY_N);

  3. By justfrank on Feb 11, 2009

    Better if

    WHERE term_id IN

    and not =

    4th line

Post a Comment