How to List All Categories, Pages and Their ID in WordPress

Posted in Wordpress Development on 16 December 2010 2 comments

If you are a developer, in some cases you need to get all categories and their IDs. You might start referring to wordpress codex but most likely you will end up with no solution, just like me. Rather than counting on wordpress’s built-in function, you can write your own MySQL query to accomplish this.

MySQL query that pulls all categories from database

<?php
 
$result = mysql_query("SELECT ".$table_prefix."terms.term_id, ".$table_prefix."terms.name,".$table_prefix."term_taxonomy.taxonomy FROM ".$table_prefix."terms INNER JOIN ".$table_prefix."term_taxonomy ON ".$table_prefix."terms.term_id = ".$table_prefix."term_taxonomy.term_id WHERE ".$table_prefix."term_taxonomy.taxonomy = 'category'");
 
while ($row = mysql_fetch_assoc($result)) {
// uncomment the line below to view the content of $row
// var_dump($row);
 
// category ID = $row['term_id']
// category name = $row['name']
 
echo $row['name'].' - ID '.$row['term_id'].'<br />';
}
 
?>

$table_prefix is a variable declared in wp-config.php, it carries value “wp_” by default unless you changed the setting. It is your SQL tables’ prefix.

WordPress stores all category, tags, etc in wp_term_taxonomy table so we can load all categories name and ID from there.

What about Pages?

<?php
 
$result = mysql_query("SELECT post_title, ID FROM ".$table_prefix."posts WHERE post_type = 'page' AND post_status = 'publish';");
 
while ($row = mysql_fetch_assoc($result)) {
// uncomment the line below to view the content of $row
// var_dump($row);
 
// page ID = $row['ID']
// page name = $row['post_title']
 
echo $row['post_title'].' - ID '.$row['ID'].'<br />';
}
 
?>

WordPress stores all pages in wp_posts table, but with post_type set as “page”.

Hope this helps.

 

Posted by Zen on 16 December 2010 • 8,067 visits 2 comments
Tags :


or Subscribe to specific category only :




  - 2 Comments


Frank Torres says:

Awesome code! Just an FYI, if you’re using this in a function (like I am), you need to have “global $table_prefix;” (no quotes) prior to the line that starts “$result = mysql_query(“.

Shir Gans says:

Hi, I’ve been looking for a solution in google… but nothing. It was really hard to get this piece of code. Thanks !

Leave a Reply

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Previous Post
«
Next Post
»