Skip to content

Instantly share code, notes, and snippets.

@seebeen
Created February 28, 2021 15:46
Show Gist options
  • Save seebeen/9b4a62f3af26ff778b9900fefc001444 to your computer and use it in GitHub Desktop.
Save seebeen/9b4a62f3af26ff778b9900fefc001444 to your computer and use it in GitHub Desktop.
WP recent comments + POST link
<?php
namespace Oblak\Addons;
use WP_Comment;
use WP_Comment_Query;
class RecentComments
{
private static ?array $comments = null;
private static RecentComments $instance;
private function __construct() {}
public static function getInstance()
{
return ( is_null(self::$instance) )
? self::$instance = new self
: self::$instance;
}
/**
* Retrieves ALL comments
*
* @param int $comment_no Number of comments to retrieve. -1 for all comments
* @param string $orderby How to order comments
* @return WP_Comment[] Comments array
*/
public static function getComments(int $comment_no, string $orderby) : array
{
if ( !is_null(self::$comments) ) :
return self::$comments;
endif;
$args = [
'number' => $comment_no,
'orderby' => $orderby,
'type__in' => ['comment']
];
$cq = new WP_Comment_Query($args);
return self::$comments = $cq->get_comments();
}
/**
*
* @param WP_Comment $comment Comment to format and get data for
* @param int $word_count Word count for comment text
* @return array Formatted Comment data array
*/
public static function formatComment(WP_Comment $comment, int $word_count = 55) : array
{
return [
'author' => $comment->comment_author,
'post' => get_the_title($comment->comment_post_ID),
'link' => get_permalink($comment->comment_post_ID),
'text' => wp_html_excerpt(wp_trim_words($comment->comment_content, $word_count), 9999),
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment