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:


/* 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:

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.


 '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 '

' . $title . '

'; /* 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 '
    '; 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); } ?>
  • comment_post_ID); ?>

    says:

    comment_content); ?>
  • '; /* 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 ); ?>

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
WordPress custom form plugins

5 Best WordPress Custom Form Plugins You Should Consider

Author: John Hughes
Last Updated: May 25th, 2023

Forms are one of the most important components of any website. We use forms for everything, from logins to checkout pages, support requests, leaving comments, and much more. Adding forms to WordPress is simple, but creating custom forms is a different matter entirely. With the right WordPress custom form plugin, you can ask users for any […]

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

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.