Support » Fixing WordPress » Retrieve latest comment from a specific post type and with a specific post tag

  • Resolved Alin Ionut

    (@c3dry2k)


    Is it possible to retrieve the latest x comments from a specific post type with a specific tag slug?

    For example, I use a specific code to retrieve posts from x category that have the same tag slug like the current post.

    <?php
    	 $posttags = get_the_tags();
    	if ($posttags) {
    	foreach($posttags as $tag) {
    	 query_posts('category_name=x"&showposts=10"&tag=' . $tag->slug .'');
    	 }
    	 }?>

    Now I want to do the same think, but for comments. I try this, but it retrieve the same thing, latest overall 10 comments.

    <?php $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    $comments = get_comments('status=approve&number=10&tag=' . $tag->slug .'');
    }} ?>

    Little help, please.

Viewing 10 replies - 1 through 10 (of 10 total)
  • Now I try with this code, but the same result, in last 5 comments overall.

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    $args = array(
        'number' => 5,
    	'tag' => ''. $tag->slug .'',
        'orderby' => 'date',
        'order' => 'DESC'
      );
    }}?>
    <?php $comments = get_comments($args);
     foreach($comments as $comment) :
        echo($comment->comment_author . '<br />' . $comment->comment_content);
    endforeach;?>
    Moderator keesiemeijer

    (@keesiemeijer)

    Hi Alin Ionut

    You can’t use taxonomy arguments in get_comments(). As a workaround you’ll first need to get all posts (ids) with the tag assigned that also have comments. Then use the ‘post_in’ argument in get_comments().
    http://codex.wordpress.org/Function_Reference/get_comments

    Put this in your (child) theme’s functions.php

    if ( !is_admin() ) {
    
    	add_filter( 'query_vars', 'add_has_comments_query_var' );
    
    	/**
    	 * Adds query var 'has_comments' to the public query vars
    	 *
    	 * @param array   $query_vars
    	 * @return array
    	 */
    	function add_has_comments_query_var( $query_vars ) {
    
    		$query_vars[] = 'has_comments';
    
    		return $query_vars;
    	}
    
    	add_filter( 'posts_where', 'posts_where_has_comments', 99, 2 );
    
    	/**
    	 * Where clause sql if the 'has_comments' query var is used.
    	 *
    	 * @param string  Where clause
    	 * @param array   Query object
    	 * @return string
    	 */
    	function posts_where_has_comments( $where, $query ) {
    		global $wpdb;
    
    		if ( !$query->get( 'has_comments' ) ) {
    			return $where;
    		}
    
    		$where .= " AND $wpdb->posts.comment_count > 0";
    
    		return $where;
    	}
    }

    btw:
    consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost. Or create a plugin with the functions.php code above.

    Now you can get the comments like this:

    <?php
    
    // Query for posts (ids) with term ids that have comments.
    $args = array(
    	'fields'         => 'ids',
    	'post_type'      => array( 'post' ),
    	'posts_per_page' => -1, // all posts
    	'has_comments'   => true, // only posts that have comments
    	'tax_query'      => array(
    		array(
    
    			'taxonomy' => 'post_tag',
    			'field'    => 'id',
    
    			// Change the term ids here
    			'terms'    => array( 173, 55 ),
    		),
    	),
    );
    
    // The query
    $post_id_query = new WP_Query( $args );
    
    // Clean up query globals after query/
    wp_reset_postdata();
    
    // Check if posts where found.
    if ( $post_id_query->have_posts() ) {
    
    	// Add post ids to the 'post__in' argument
    	$args = array(
    		'post__in' => $post_id_query->posts,
    	);
    
    	// Get the comments
    	$comments = get_comments( $args );
    
    	// Comment Loop
    	if ( $comments ) {
    		foreach ( $comments as $comment ) {
    			// Display comments
    			echo '<p>' . $comment->comment_content . '</p>';
    			echo '<p> By' . $comment->comment_author  . '</p>';
    		}
    	} else {
    		echo 'No comments found.';
    	}
    }
    ?>

    I’ve used term ids in this example.
    Change the term ids to the ones you need here:

    'terms'    => array( 173, 55 ),

    I hope this all makes sense 🙂

    Sorry, but is not what I’m looking for. I do not want to retrieve manually ID for tags, I want to be automatic, to take the tag of the current post, and display all the comments of that specific posts tag.

    Moderator keesiemeijer

    (@keesiemeijer)

    Wrap it in a tag loop.

    Try it with this:

    <?php
    // get post tags
    $posttags = get_the_tags( $post->ID );
    
    if ( $posttags ) {
    
    	foreach ( $posttags as $tag ) {
    
    		// Query for posts (ids) with term ids that have comments.
    		$args = array(
    			'fields'         => 'ids',
    			'post__not_in'  => array( $post->ID ),
    			'post_type'      => array( 'post' ),
    			'posts_per_page' => -1,
    			'has_comments'   => true, // only posts that have comments
    			'tax_query'      => array(
    				array(
    
    					'taxonomy' => 'post_tag',
    					'field'    => 'slug',
    					'terms'    => $tag->slug, // slugs
    				),
    			),
    		);
    
    		// The query
    		$post_id_query = new WP_Query( $args );
    
    		// Clean up query globals after query/
    		wp_reset_postdata();
    
    		// Check if posts where found.
    		if ( !$post_id_query->have_posts() ) {
    			continue;
    		}
    
    		// Add post ids to the 'post__in' argument
    		$args = array(
    			'post__in' => $post_id_query->posts,
    			'number' => 5
    		);
    
    		// Get the comments
    		$comments = get_comments( $args );
    
    		// Comment Loop
    		if ( $comments ) {
    			echo '<h3>Comments for ' . $tag->name . '</h3>';
    			echo '<p>';
    			foreach ( $comments as $comment ) {
    				// Display comments
    				echo $comment->comment_author  . '<br/>';
    				echo $comment->comment_content . '<br/><br/>';
    			}
    			echo '</p>';
    		}
    	}
    }
    ?>

    Works perfect. Thank you sir.
    Now I need someting a little more, I forgot to mention earlier.

    Is it possible to retrive and comments from woocommerce product in the same loop of course? Sku product = post tag

    My code is

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
     foreach($posttags as $tag) {
    $args = array( 'post_type' => 'product', 'posts_per_page' => 1,'meta_key' => '_sku', 'meta_value' => '' . $tag->slug .'', 'compare' => '=');
    }
    }
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
    Moderator keesiemeijer

    (@keesiemeijer)

    Can you explain a bit more.

    Do you want to include post tags from a custom post type ‘product’?

    If so add the ‘pruduct’ post type to the ‘post_type’ array.

    // Query for posts (ids) with term ids that have comments.
    		$args = array(
    			'fields'         => 'ids',
    			'post__not_in'  => array( $post->ID ),
    			'post_type'      => array( 'post', 'product', ),
    			'posts_per_page' => -1,
    			'has_comments'   => true, // only posts that have comments
    			'tax_query'      => array(
    				array(
    
    					'taxonomy' => 'post_tag',
    					'field'    => 'slug',
    					'terms'    => $tag->slug, // slugs
    				),
    			),
    		);

    I want that the loop above to retrive not just the comment from posts with the same tag, and the comments from products that have _sku the same as the curent post tag.

    1. Post patent have the tag ‘test’
    2. Another posts that have comments on it, and with the same tag ‘test’.
    Until here everyting is great.
    3. Post_type = product with sku ‘test’ have comments, not tag ‘test’!
    4. Combine all comments from posts with tag ‘test’ and products with sku ‘test’.

    Moderator keesiemeijer

    (@keesiemeijer)

    If I understand correctly (from your code) ‘_sku’ is a custom field used for ‘product’ post type posts.

    Try it with this:

    <?php
    // get post tags
    $posttags = get_the_tags( $post->ID );
    
    if ( $posttags ) {
    
    	// array to store post ids in (that have comments)
    	$post_ids = array();
    
    	// Default query args for posts (ids) that have comments.
    	$default_args = array(
    		'fields'         => 'ids',
    		'post__not_in'  => array( $post->ID ),
    		'posts_per_page' => -1,
    		'has_comments'   => true, // only posts that have comments
    	);
    
    	foreach ( $posttags as $tag ) {
    
    		// tax args
    		$tax_args = $default_args;
    		$tax_args['post_type'] = 'post';
    		$tax_args['tax_query'] = array(
    			array(
    
    				'taxonomy' => 'post_tag',
    				'field'    => 'slug',
    				'terms'    => $tag->slug, // slugs
    			),
    		);
    
    		// tax query
    		$tax_query = new WP_Query( $tax_args );
    
    		if ( isset( $tax_query->posts ) && is_array( $tax_query->posts ) ) {
    			$post_ids = array_merge( $post_ids, $tax_query->posts );
    		}
    		wp_reset_postdata();
    
    		// meta args
    		$meta_args = $default_args;
    		$meta_args['post_type'] = 'product';
    		$meta_args['meta_query'] = array(
    			array(
    				'key'     => '_sku',
    				'value'   => $tag->slug,
    			),
    		);
    
    		// meta query
    		$meta_query = new WP_Query( $meta_args );
    
    		if ( isset( $meta_query->posts ) && is_array( $meta_query->posts ) ) {
    			$post_ids = array_merge( $post_ids, $meta_query->posts );
    		}
    		wp_reset_postdata();
    
    		$post_ids = array_unique( $post_ids );
    
    		// Check if posts where found.
    		if ( empty( $post_ids ) ) {
    			continue;
    		}
    
    		// Add post ids to the 'post__in' argument
    		$args = array(
    			'post__in' => $post_ids,
    			'number' => 5
    		);
    
    		// Get the comments
    		$comments = get_comments( $args );
    
    		// Comment Loop
    		if ( $comments ) {
    			echo '<h3>Comments for ' . $tag->name . '</h3>';
    			echo '<p>';
    			foreach ( $comments as $comment ) {
    				// Display comments
    				echo $comment->comment_author  . '<br/>';
    				echo $comment->comment_content . '<br/><br/>';
    			}
    			echo '</p>';
    		}
    	}
    }
    ?>

    Works like a charm, thank you sir.

    Moderator keesiemeijer

    (@keesiemeijer)

    You’re welcome 🙂

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘Retrieve latest comment from a specific post type and with a specific post tag’ is closed to new replies.