我有以下查询来获取最新评论:
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,30) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 10";
$comments = $wpdb->get_results($sql);
我还希望获得每条评论的帖子名称(slug),而不会为每条评论运行查询。您能否建议对上述查询进行修改以实现此目的?更好的是,我可以使用内置的Wordpress功能吗?
基本上我需要:
$comments = array ( 'comment_object' => ... , 'post_name' => ... )
答案 0 :(得分:1)
来自我自己的最近评论代码,包含少量修改:
/**
* @return object
*/
function recent_comments_query($limit)
{
global $wpdb;
$sql = "SELECT DISTINCT ID,
post_title,
post_name, // <- post name
post_password,
comment_ID,
comment_post_ID,
comment_author AS author,
comment_date_gmt,
comment_approved,
comment_type,
comment_author_url AS url,
SUBSTRING(comment_content, 1, 200)
AS comment_content
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts
ON (
$wpdb->comments.comment_post_ID = $wpdb->posts.ID
)
WHERE comment_approved = '1'
AND comment_type = ''
AND post_password = ''
ORDER BY comment_date_gmt DESC
LIMIT $limit";
return $wpdb->get_results($sql);
}
您将获得一个$limit
个结果或NULL
的对象。