Blog / plugins / Get the latest comments for a custom post type in WordPress

Get the latest comments for a custom post type in WordPress

Cristian Antohe
Last Updated: 20/05/11

Custom post types for WordPress support comments, however the API doesn’t allow for retrieving those comments.

So in order to get the latest comments from your custom post type you need to do an sql query that does a LEFT OUTER JOIN between the comments table and the posts table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
/* Get recent comments */
global $wpdb;
 
$sql = "SELECT * 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 = '' AND post_type='your_custom_post_type' ORDER BY comment_date_gmt DESC LIMIT 5";
 
$comments = $wpdb->get_results($sql);
 
foreach ($comments as $comment) {
  // we need the comment comment user_id in case it's a logged in user so we can echo the display name and not username
  if ($comment->user_id != 0) {
    $curent_userdata = get_userdata($comment->user_id);
    echo $curent_userdata->display_name;
  } else {
    echo strip_tags($comment->comment_author);
  }
 
  // the permalink for the comment
  echo get_permalink($comment->ID) . '#comment-' . $comment->comment_ID;
 
  // the post title where that comment was posted
  echo $comment->post_title; 
 
  // display the comment content
  echo strip_tags($comment->comment_content);
}

The important bit is in the SQL declaration:

1
post_type='your_custom_post_type'

Let’s transform this into a widget

I’m not going to go through all the steps needed to create a widget for WordPress, instead I’ll just give you the code so you can use in your own projects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
 
<?php
/*
Plugin Name: Latest CPT Comments Plugin
Plugin URI: http://www.cozmoslabs.com/
Description: Display the latest comments on a custom post type
Version: 0.1
Author: Cristian Antohe
Author URI: http://cozmoslabs.com
License: GPL2
 
== Copyright ==
Copyright 2011 Reflection Media (wwww.reflectionmedia.ro)
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
add_action( 'widgets_init', 'cl_cpt_comments_load_widgets' );
 
function cl_cpt_comments_load_widgets() {
	register_widget( 'cl_cpt_comments_Widget' );
}
 
class cl_cpt_comments_Widget extends WP_Widget {
 
	/**
	 * Widget setup.
	 */
	function cl_cpt_comments_Widget() {
		/* Widget settings. */
		$widget_ops = array( 'classname' => 'cl_cpt_comments_widget', 'description' => __('A widget that displays your latest custom post type comments', 'cl_cpt_comments_widget') );
 
		/* Widget control settings. */
		$control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'cl_cpt_comments_widget' );
 
		/* Create the widget. */
		$this->WP_Widget( 'cl_cpt_comments_widget', __('Latest custom post type comments', 'cl_cpt_comments_widget'), $widget_ops, $control_ops );
	}
 
	/**
	 * How to display the widget on the screen.
	 */
	function widget( $args, $instance ) {
		extract( $args );
 
		/* Our variables from the widget settings. */
		$title = apply_filters('widget_title', $instance['title'] );
		$number = $instance['number'];
 
		/* Before widget (defined by themes). */
		echo $before_widget;
 
		/* Display the widget title if one was input (before and after defined by themes). */
		if ( $title )
			echo '<h3 class="widget-title">' . $title . '</h4>';
 
		/* Get recent comments */
		global $wpdb;
		$sql = "SELECT * 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 = '' AND post_type='your_custom_post_type' ORDER BY comment_date_gmt DESC LIMIT $number";
		$comments = $wpdb->get_results($sql);
		echo '<ul class="cpt-comments">';
		foreach ($comments as $comment) {
			if ($comment->user_id != 0) {
				$curent_userdata = get_userdata($comment->user_id);
				$current_comment_display_name = $curent_userdata->display_name;
			} else {
				$current_comment_display_name = strip_tags($comment->comment_author);
			}						
		?>
			<li class="cpt-comment">
				<p class="comment-cpt-title"><a href="<?php echo get_permalink($comment->ID); ?>#comment-<?php echo $comment->comment_ID; ?>" rel="bookmark"><?php echo get_the_title($comment->comment_post_ID); ?></a></p>
				<p class="comment-author"><?php echo $current_comment_display_name  ?> says:</p><a class="comment-text-side" href="<?php echo get_permalink($comment->ID); ?>#comment-<?php echo $comment->comment_ID; ?>" title="<?php echo strip_tags($comment->comment_author); ?> on <?php echo $comment->post_title; ?>"><?php echo strip_tags($comment->comment_content); ?></a>
			</li>
		<?php 
		}
		echo '</ul>';
 
		/* After widget (defined by themes). */
		echo $after_widget;
	}
 
	/**
	 * Update the widget settings.
	 */
	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
 
		/* Strip tags for title and name to remove HTML (important for text inputs). */
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['number'] = strip_tags( $new_instance['number'] );
 
		return $instance;
	}
 
 
	function form( $instance ) {
 
		/* Set up some default widget settings. */
		$defaults = array( 'title' => __('Latest CPT Comments'), 'number' => __('5'));
		$instance = wp_parse_args( (array) $instance, $defaults ); ?>
 
		<!-- Widget Title: Text Input -->
		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?></label>
			<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:90%;" />
		</p>
 
		<!-- Number of posts -->
		<p>
			<label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e('Number of posts to show:'); ?></label>
			<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" value="<?php echo $instance['number']; ?>" size="3" />
		</p>
 
 
 
 
	<?php
	}
}
 
?>

Next you need to copy this code, put it inside the plugins directory, activate the plugin and you’re ready to go. Don’t forget to change the custom post type to your own.

From the blog

Related Articles

A Beginner’s Guide to Custom Post Types

Author: Lindsay Liedke
Last Updated: July 1st, 2020

WordPress Custom Post Types are the best way to create intuitive content types. This is done by having a clear differentiation between the different types of content, adding just the required parameters and fields to them, and therefore removing clusters from the sometimes overloaded WordPress admin menu. Out of the box, the WordPress content management […]

Continue Reading

Show Custom Fields in WordPress

Author: Cristian Antohe
Last Updated: April 5th, 2023

Adding custom fields to your WordPress site helps you display additional information about your content and can improve SEO for Google and other search engines. But how to show custom fields can be a pretty challenging thing to achieve by non-technical users By default, WordPress gives you the possibility to add custom fields (sometimes called […]

Continue Reading

WordPress Creation Kit – a sparkling new custom field, taxonomy and post type creator

Author: Cristian Antohe
Last Updated: December 20th, 2023

WordPress Creation Kit consists of three brand new modules that can help you with the tough task of creating and maintaining custom post types, custom taxonomies and most importantly, custom fields and metaboxes for your posts, pages or CPT's. Why another plugin for this? We've actually started working on this more then a year ago, […]

Continue Reading

10 thoughts on “Get the latest comments for a custom post type in WordPress

    wow. nice information you got here. I hope that you can elaborate more on the sidebar topic. because one of my Articles have the same problem with that. so if you can tell me more how to fix it, it would be nice!
    Thanks!

    Reply

    Just the query I was looking for. The widget is an added bonus. Thanks for helping out the wp community.

    Reply

    it’s awesome, but is there anyway to add pagination to this?

    Reply

    Don’t work on my custom post type, only retrieve the comment without:
    AND post_type=’movies’

    Reply

    You can even way (short record)

    $args = array(
    ‘parent’=>0
    ‘post_type’ => ‘custom-post-type’,
    ‘number’ => ‘1’,
    ‘orderby’ => ‘date’,
    ‘order’ => ‘DESC’
    );

    $comments = get_comments($args);
    foreach($comments as $comment) :
    echo($comment->comment_author . ” . $comment->comment_content);
    endforeach;

    Reply

    Hi there! Thanks a lot for this solution. Is it also possible to show the latest comment for a specific posttype as a shortcode instead?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.