我想获得帖子ID的最新评论的日期gmt。我想获得的结果是字符串。
有人能帮我如何将结果设置为字符串吗:
function GetLastCommentDate( $postId ) {
global $wpdb;
$dateOutput = '0000-00-00 00:00:00';
$commentRes= $wpdb->get_results("SELECT DISTINCT `comment_date_gmt` FROM `wp_comments` WHERE `comment_approved` ='1' AND `comment_post_ID` = '". $postId. "' ORDER BY `comment_date_gmt` DESC LIMIT 1");
if(!empty($commentRes)) {
$dateOutput = ...........
}
return $dateOutput;
}
一个答案是这样的:
$commentRes= $wpdb->get_results("SELECT DISTINCT `comment_date_gmt` as `comment_date_gmt` FROM `wp_comments` WHERE `comment_approved` ='1' AND `comment_post_ID` = '". $postId. "' ORDER BY `comment_date_gmt` DESC LIMIT 1");
if(!empty($commentRes)) {
foreach($commentRes as $comment) {
$dateOutput=$comment->comment_date_gmt;
}
}
return $dateOutput;
但是如何避免前臂循环呢?只有一行(sql限制设置为1)。
您不需要直接查询wordpress数据库。WP提供了一个API来检索它。
$comments = get_comments( array(
'post_id' => $post->ID,
'orderby' => 'comment_date_gmt',
'status' => 'approve',
'number' => 1
) );
查看此API参考资料。指定数字为1只返回最后一条注释。
最后一条评论的日期值可以检索为$comments[0][date']
既然您想从外部使用它,请在php代码的顶部包含以下内容
require('/the/path/to/your/wp-blog-header.php');
查看这个单词press doumentation
如果出现循环外错误,请尝试添加此代码。
循环从这里开始:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
并在此结束:
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
我想你想要这样的东西;
$commentRes= $wpdb->get_row(
"SELECT `comment_date_gmt` FROM `wp_comments` ".
"WHERE `comment_approved` ='1' AND `comment_post_ID` = '$postId' ".
"ORDER BY `comment_date_gmt` DESC LIMIT 1");
if(!empty($commentRes))
$dateOutput = date("Y-m-d H:i:s", $commentRes->comment_date_gmt);
我在寻找其他东西时偶然发现了这个。我知道这个问题很老,答案也很简单,但有人可以像我一样找到它,我想添加另一个更新的解决方案。
function GetLastCommentDate( $postId ) {
$dateOutput = false; //this will make easier to check if there are no comments
//get_comments() args https://codex.wordpress.org/Function_Reference/get_comments
$args = array(
'post_id' => $postId, //just comments of this post
'number' => 1, //just one comment
'order_by' => 'comment_date_gmt', //order by comment date gmt
'order' => 'DESC', //latest first
);
//retrieve comments
$comments = get_comments($args);
if ($comments){
$dateOutput = $comments[0]->comment_date;
}
return $dateOutput;
}
你可以像这样在任何你想用的地方使用它:
$postId = '12345';
$lastCommentDate = GetLastCommentDate($postId) ?: 'Never';
echo $lastCommentDate;