WordPress term list of a post

In WordPress I am building an index page where I list in a table all the articles of my blog. Every row of this table has the following structure: post title, terms belonging to a certain group. For example, if it were about movies:

 Blade Runner       | noir, science fiction
 Gone with the Wind | dramatic

The point is: when I have multiple terms there is some weird error that returns an empty set or sometimes the wrong terms are listed. And I am quite puzzled because I can’t figure out why this happens. This is how I fetch the data.

Read More
//Loops through the articles in the table wp_posts
foreach($results as $result){
    $metaStr = "";
    $id = $result->ID;
    $query = "
        SELECT name 
        FROM wp_term_relationships 
        INNER JOIN wp_terms
        ON term_id = term_taxonomy_id
        WHERE object_id = $id AND term_taxonomy_id IN (6, 7, 8, 9, 14, 15, 18, 22, 24, 30)
    ";
    $metas = $wpdb->get_results($query);
    $count = 0;
    foreach($metas as $meta){
        if($count > 0){
            $metaStr .= "<br />";
        }
        $metaStr .= $meta->name;
        $count++;
    }
    print $metaStr;
}

Anybody can help? What am I doing wrong? Is there a better way to do this?
Cheers

Related posts

Leave a Reply

2 comments

  1. Put the following function and just pass the post id, In your case $result->ID;

    function my_get_term_of_post($postId){
    $metaStr="";
    $term_list = wp_get_post_terms($postId, 'console', array("fields" => "all"));
    $i=1;
    foreach($term_list as $termSingle){
        if($i==1)
         $metaStr=$termSingle->name;
        else
         $metaStr.= "<br/>".$termSingle->name;
        $i++;
    }
    return $metaStr;
    

    }

    $term_list= my_get_term_of_post($result->ID);

  2. Never store multiple values in a single column!

    Rather change your table design and add another table for the mapping. Like

    posts table
    ------------
    id
    title
    
    
    tags table
    ------------
    id
    name
    
    
    post_tags table
    ------------------
    post_id
    tag_id
    

    That way you will have a defined list of tags, a fast way to query the data and it is normalized too.