I’m having a small query issue that maybe you can help me with. I am trying to get all comments from a post that has a particular comment meta. This is what I have so far:
$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments INNER JOIN wp_commentmeta WHERE comment_post_ID = '256' AND comment_approved = '1' AND meta_key = 'bestcomment' AND meta_value = 'yes' "); ?>
<ul id="bestcomment">
<h2>Best Comment</h2>
<?php
if ( $comments ) : foreach ( (array) $comments as $comment) :
echo '<li class="recentcomments">' . sprintf(__('%1$s on %2$s'), get_comment_author_link(), '<a href="'. get_comment_link($comment->comment_ID) . '">' . get_the_title($comment->comment_post_ID) . '</a>') . '</li>';
endforeach; endif;?></ul>
This post should only have one comment. Unfortunately, the query is displaying the same result 24 times. So there has to be something wrong with the loop. Thoughts?
There is nothing wrong with the loop. The problem is that your query produces
cartesian product(CROSS JOIN) because you didn’t specify the column on which the two tables should be link.The fastest answer I can give is to define the linking columns on the
ONclause,just change
ColumnNameinto the real name of the column in your table.To learn more about
JOIN, please take a look at the article below,