• Resolved gcarson

    (@gcarson)


    After trying to figure it out on my own for a few hours, I seem to be going around in circles. Basically, I’m trying to get the tag of a post from the database from a page outside of wordpress. I use wordpress as a CMS for this site and not really a blog. I’m passing the post ID in the url and using that as my starting point.

    I figured somewhere in wp_posts it would store the tags of the post but it doesn’t appear as so.

    I found in wp_term_relationships, I can search in object_id for the post ID to get the categories and tags of the post. But this doesn’t tell me if the id is a category or tag.

    So then I have to search in wp_term_taxonomy to find which of the id’s I just pulled is a tag id (my posts only have 1 tag and 1 category).

    Then, once i have the tag id of the post, I can look in wp_terms to get the name of the tag.

    That seems like a lot of searching to get the name of a tag associated with a post. Is there something I’m missing or do I have to do all these database queries to get the name of a tag?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Yes. If you are trying to access this information outside of WordPress you cannot use the helpful built-in WordPress functions like get_term_by() https://codex.www.ads-software.com/Function_Reference/get_term_by.

    As such, it will be necessary to query the database for this information. I believe this is what you are looking for:

    SELECT name
    FROM wp_term_relationships
    JOIN wp_term_taxonomy
    ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
    JOIN wp_terms
    ON wp_terms.term_id = wp_term_taxonomy.term_id
    WHERE object_id = ‘<INSERT POST ID HERE>’ AND taxonomy = ‘post_tag’

    This query will do the necessary joins and return your tag name. You can use SELECT * to return all of the information for a given post id.

    Thread Starter gcarson

    (@gcarson)

    Wow, thank you for that. I’m not good with sql searches, I probably would have done a search, saved the result, did another search, saved the result, etc etc. The JOIN and ON commands are a little beyond my comprehension.. but with your example, I can see how it works. And work it did on the first try. Wow, thank you for this.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get a Post's Tag from Database’ is closed to new replies.