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.
//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
Put the following function and just pass the post id, In your case $result->ID;
}
$term_list= my_get_term_of_post($result->ID);
Never store multiple values in a single column!
Rather change your table design and add another table for the mapping. Like
That way you will have a defined list of tags, a fast way to query the data and it is normalized too.