Support » Developing with WordPress » get category id

  • Hi!

    I wonder if there’s any simple way for a not-so-savvy php user to get all ids for the categories present on a website. Best thing: show the category name and then the id number. It will be really helpful as I have hundreds categories and right now I am getting the id from the WP dashboard.

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • You can do searches in the Code Reference
    Search for get_cat

    But your question does not state where you wanted to show these ID numbers. I would expect that the WP dashboard is the only place to show them. Also, I can see having hundreds of posts, but not hundreds of categories. Simplify.

    Moderator bcworkz


    Use get_categories()!

    OK, not that simple. It returns an array of WP_Term objects representing each category. You then need to loop through the result and echo out the name and term_id properties of each.

    The other question is where to put this code? It ought to go on a theme template somewhere. But you likely do not want such a list on your usual site pages. I would put the code on a custom page template and make a private page based on the template. Copy your theme’s page.php, renaming it page-{$page_slug}.php. For example: if the page you create has the slug my-cats, the file name should be page-my-cats.php. Replace the call to the_content(); with your category code.

    Keep a backup of your file, as it will be lost when your theme updates. To protect your changes from theme updates, create a child theme.

    Like many things coding related, something simple can escalate into complicated. However, much of the complications in this case are setting you up to easily make other customizations in the future. Making custom templates and keeping them in a child theme will continue to serve you well.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘get category id’ is closed to new replies.