2

How can I get comments from multiple post type? I want to display 5 comments from my different post types pages.

<?php 

$defaults = array(
    'number' => 5,
    'post_type' => array('post','authors','movies')
);
$comments = get_comments($defaults);
 ?>
1

It looks like WP_Comment_Query() only supports a single post type.

You can adjust it, by using the comments_clauses filter.

Try for example:

$defaults = array(
    'number'    => 5,
    'post_type' => array( 'post','authors','movies' ),
);
add_filter( 'comments_clauses', 'wpse_121051', 10, 2 );     
$comments = get_comments($defaults)

where

 /**
  * Support for multiple post types for comments
  *
  * @param array $clauses
  * @param object $wpqc WP_Comment_Query
  * @return array $clauses
  */   
 function wpse_121051( $clauses, $wpqc )
 {
    global $wpdb;

    // Remove the comments_clauses filter, we don't need it anymore. 
    remove_filter( current_filter(), __FUNCTION__ );

    // Add the multiple post type support.
    if( isset( $wpqc->query_vars['post_type'][0] ) )
    {

        $join = join( "', '", array_map( 'esc_sql', $wpqc->query_vars['post_type'] ) );

        $from = "$wpdb->posts.post_type = '" . $wpqc->query_vars['post_type'][0] . "'";                         
        $to   = sprintf( "$wpdb->posts.post_type IN ( '%s' ) ", $join );

        $clauses['where'] = str_replace( $from, $to, $clauses['where'] );
    }  

    return $clauses;
 }

The plugin:

As kindly suggested by @kaiser, I made a small plugin to add multiple post types support to WP_Comment_Query() and get_comments(). Let's hope this missing feature will be supported by the WordPress core in the near future ;-)

| improve this answer | |
  • ok great, I just updated the answer that should be more easier to work with. – birgire Nov 3 '13 at 9:52
  • 1
    Cool thing! Should be a plugin :) – kaiser Nov 3 '13 at 21:04
  • 1
    @kaiser: thanks, ... here we go, a tiny plugin with a long name ;-) – birgire Nov 5 '13 at 21:11
2

Just in case anyone comes across this question, WordPress now accepts an array for the post_typeparameter for get_comments()

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.