WordPress: Display All Categories with ID

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.

Display All Categories with ID

<?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.

Display All Page with ID

<?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”.

 

source: zenverse

Artikel terkait:   WordPress: Plugin Require Another Plugin Installed

Isi Komentar

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *

This site uses Akismet to reduce spam. Learn how your comment data is processed.