2013-07-09 53 views
0

我想获得日期gmt最新评论的帖子ID。结果我想要得到一个字符串。WordPress的SQL查询最后评论日期

有人可以帮我如何设置导致成字符串:

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; 

但如何避免foreach循环?只有一行(sql限制设置为1)。

+0

你试过'的var_dump($ commentRes);'看它所包含的内容? – jeroen

+0

'SELECT max(comment_date_gmt)FROM wp_comments WHERE comment_approved ='1'AND comment_post_ID ='“。$ postId。”'“'should do – Orangepill

回答

1

您无需直接查询wordpress数据库。 WP提供了一个API来检索这个。

$comments = get_comments(array(
    'post_id' => $post->ID, 
    'orderby' => 'comment_date_gmt', 
    'status' => 'approve', 
    'number' => 1 
)); 

看看这个API reference。将数字指定为1只会返回最后的评论。

的最后一个注释的日期值可以被检索为$评论[0] [“日期”]

现在,你想用这个来自外部,包括在你的PHP代码顶级以下

require('/the/path/to/your/wp-blog-header.php'); 

退房this wordpress 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; ?> 
+0

这是不可能的使用这个函数我需要它在你的循环之外 – user2565035

+0

我已编辑我的答案检查出来 – oat

0

我想你想是这样的;

$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); 
0

我在寻找别的东西的时候偶然发现了这个。我知道这个问题很古老,也有aswers,但有人可以像我一样找到它,并且我想添加另一个更新的解决方案。

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;