How to get Categories by user?

What would be the SQL query to get the Categories for a given site?

The reason, I would like to use Categories a user has selected to focus ad placement on respective sites. For example, if a user selects the categories Motorcycles, Cooking, and Photography, then I can show related ads on their site.

I've been looking through the database and I cannot for the life of me find where each site's selected categories are stored.


  • Tedster
    • The Incredible Code Injector

    Okay, I need just a little more help with this :smiley:

    (bcat) and get_terms is good to know, but what should I do with them? I know it's a lot to ask but I'm running around in 20 different directions and by eyes are glassing over from reading tutorials and codex and forums.... what I really need is a starting point.

    What is the code, presumably to place in my theme's functions.php file, which will display the categories to which that site currently belongs?

    For example, if a site admin selected categories Hobbies, Travel and Photography for that particular site (it's a multisite using subdomains, if that matters), I would like just after every post or page to echo...

    Categories: Hobbies, Travel, Photography

    If possible, I would also like the category ID like so...

    Categories: Hobbies (3), Travel (7), Photography (12)

    I know it's a lot to ask, but this bit of code will show me what I need to know so I can stop running in circles. Please help? Thanks :slight_smile:

  • Paul
    • The Green Incsub


    Here you go. You can drop this little function into your functions.php or wherever. It is a start.

    function get_site_categories() {
       global $current_site, $current_blog;
       // The bcat taxonomy is only registered on the primary site. So before it can be queries you need to switch to that site.
       switch_to_blog( $current_site->blog_id );
       $site_categories = wp_get_object_terms($current_blog->blog_id, SITE_CATEGORIES_TAXONOMY);
       echo "DEBUG: site_categories<pre>"; print_r($site_categories); echo "</pre>";
       // Revert back to the current site.
  • Tedster
    • The Incredible Code Injector

    Hi Paul,

    I haven't had a chance to try your code yet but it looks like exactly what I need. I just popped in to say thanks and let you know I haven't forgotten this topic. I'm reinstalling my site and will be addressing this issue in the next day or so. Wish me luck! :slight_smile:

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.