1321941
1321941

Reputation: 2180

Wordpress: Using the category slug get the category ID using mysql query

basically, I have a cookie with the category slug stored, using this data I want to query the database and return the ID of the category.

I am new to mysql and this seems like an advanced query that may need to use joins, any help or guidance would be much appreciated.

Thank you!

Reference: http://codex.wordpress.org/File:WP3.0-ERD.png

Upvotes: 1

Views: 2632

Answers (4)

Bainternet
Bainternet

Reputation: 569

You can use the WordPress native function get_term_by ex:

$term = get_term_by('slug',$SLUG_FROM_COOKIE,'category');

and now$term is a term object so you can use $term->ID

Upvotes: 0

eggyal
eggyal

Reputation: 126055

SELECT wp_term_taxonomy.term_taxonomy_id
FROM   wp_terms
  JOIN wp_term_taxonomy USING (term_id)
WHERE  wp_term_taxonomy.taxonomy = 'category'
   AND wp_terms.slug = ?

Learn about SQL joins.

Upvotes: 1

Eduardo Reveles
Eduardo Reveles

Reputation: 2175

Well, the name and slug are stored on the same table, so something like this should do it (only mysql, no WP Query involved):

SELECT term_id as id FROM wp_terms WHERE slug = 'slug-here';

Upvotes: 0

chrisn
chrisn

Reputation: 2135

Check out the example on the page for get_category_by_slug:

<?php 
  $idObj = get_category_by_slug('slug'); 
  $id = $idObj->term_id;
?>

More importantly, if you already have the slug stored, why not just store the id along with it in order to avoid having to query for the ID each time?

EDIT: Based on your comment, it'd probably be easiest for you to add the following to any WordPress page:

define('SAVEQUERIES', true);
global $wpdb;
print_r($wpdb->queries);

and then run the original code from this post. This will enable you to see the queries that WordPress performed in order to get the category and associated data, and you can copy them and use them in your code.

Upvotes: 3

Related Questions