Retrieve category id by category slug

Views: 520 Last modified: August 02nd, 2011 Comments: 0

This function for wordpress will retrieve the category ID by the category slug. This might be useful when you access the $wp_query object directly for queried objects and the tagged slugs.

<?php
/**
 * GetCatIdBySlug()
 * Returns the category ID or false in case of failure
 * @param string $slug
 * @return mixed $query|bool
 */
function GetCatIdBySlug($slug){
    if (!is_string($slug))
        return false;

    global $wpdb;
        $query = $wpdb->get_var($wpdb->prepare("SELECT terms.term_id
                                                    FROM $wpdb->terms AS terms
                                                    INNER JOIN $wpdb->term_taxonomy AS taxonomy
                                                    ON terms.term_id = taxonomy.term_id
                                                        WHERE terms.slug = %s
                                                        AND taxonomy.taxonomy = 'category'
                                                        ", $slug));
        return ($query) ? $query : false;
}
?>
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {1+3} =  
    Anything to add ?

        You must be logged in to post a comment.