Creating a Custom ‘The Posts I Commented On’ Loop

Creating a Custom ‘The Posts I Commented On’ Loop

Tutorial Details
  • Program: WordPress
  • Version : 3.0 and higher
  • Difficulty:Beginner - intermediate
  • Estimated Completion Time: 20-30 minutes

Sometimes a WordPress developer might need custom loops which can not be generated with standard loops as category, author, index, date, archive, taxonomy etc. One of them is “the posts which I commented on“. In Q&A sites it means “the questions I answered”, so it might be needed for many developers. On base of this tutorial we can create another custom loops. Let’s go to create this section.


Step 1

Go to your theme folder and create a myanswers.php file, then copy and paste following code there:

<?php /* Template Name: myanswers */ ?>
<?php
get_header(); ?>
<?php
get_template_part( 'loop', 'myanswers' );	 
?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

We have just created template file called myanswers. It will be used for displaying our custom loop.


Step 2

Stay in your theme folder and create second file called loop-myanswers.php. And paste following code into that file:

<?php
if($wp_query->query_vars['paged']==0){$wp_query->query_vars['paged']=1;}
$querystr = "
    SELECT $wpdb->posts.* 
    FROM $wpdb->posts  inner join $wpdb->comments on $wpdb->posts.ID=$wpdb->comments.comment_post_ID 
    WHERE $wpdb->posts.post_status='publish' and $wpdb->comments.user_id=".wp_get_current_user()->ID."
    GROUP BY $wpdb->posts.ID
    ORDER BY $wpdb->posts.post_date DESC  ";

$lim_per_page=" limit ".($wp_query->query_vars["posts_per_page"]*($wp_query->query_vars['paged']-1)).",".$wp_query->query_vars["posts_per_page"];

$query_for_count = $wpdb->get_results($querystr, OBJECT);
$wp_query->max_num_pages=ceil($wpdb->num_rows/$wp_query->query_vars["posts_per_page"]);
$querystr=$querystr.$lim_per_page;
$pageposts = $wpdb->get_results($querystr, OBJECT);
 ?>

<?php if ($pageposts): ?>
 <?php global $post; 
 ?>
 
 <?php foreach ($pageposts as $post): ?>
 <?php setup_postdata($post); ?>
 
<?php
/// THIS PART IS LOOP FROM TWENTYTEN, YOU CAN CHANGE IT HOWEVER YOU WANT BEGIN
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), 
the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>

			<div class="entry-meta">
				<?php twentyten_posted_on(); ?>
			</div><!-- .entry-meta -->

	<?php if ( is_archive() || is_search() ) : // Only display excerpts for archives and search. ?>
			<div class="entry-summary">
				<?php the_excerpt(); ?>
			</div><!-- .entry-summary -->
	<?php else : ?>
			<div class="entry-content">
				<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyten' ) ); ?>
				<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
			</div><!-- .entry-content -->
	<?php endif; ?>

			<div class="entry-utility">
				<?php if ( count( get_the_category() ) ) : ?>
					<span class="cat-links">
						<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'twentyten' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?>
					</span>
					<span class="meta-sep">|</span>
				<?php endif; ?>
				<?php
					$tags_list = get_the_tag_list( '', ', ' );
					if ( $tags_list ):
				?>
					<span class="tag-links">
						<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'twentyten' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?>
					</span>
					<span class="meta-sep">|</span>
				<?php endif; ?>
				<span class="comments-link"><?php comments_popup_link( __( 'Leave a comment', 'twentyten' ), __( '1 Comment', 'twentyten' ), __( '% Comments', 'twentyten' ) ); ?></span>
				<?php edit_post_link( __( 'Edit', 'twentyten' ), '<span class="meta-sep">|</span> <span class="edit-link">', '</span>' ); ?>
			</div><!-- .entry-utility -->
		</div><!-- #post-## -->

 <?php endforeach; 
/// THIS PART IS LOOP FROM TWENTYTEN, YOU CAN CHANGE IT HOWEVER YOU WANT  END
?>
 <?php else : ?>
    <h2 class="center">Not Found</h2>
    <p class="center">Sorry, but you are looking for something that isn't here.</p>
    <?php include (TEMPLATEPATH . "/search.php"); ?>
 <?php endif; ?>
 
 <?php
echo  $wp_query->max_num_pages;
 if (  $wp_query->max_num_pages > 1 ) : ?>
				<div id="nav-below" class="navigation">
					<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Previous', 'twentyten' ) ); ?></div>
					<div class="nav-next"><?php previous_posts_link( __( 'Next<span class="meta-nav">→</span>', 'twentyten' ) ); ?></div>
				</div><!-- #nav-below -->
<?php endif; ?>

This file is for generating our custom loop in template file.


Step 3

Open theme functions file of your theme(functions.php) and add this function and filter to that file:

add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars )
{
/* Plugin Name: Parameter
Plugin URI: http://webopius.com/
Description: A plugin to allow parameters to be passed in the URL and recognized by WordPress
Author: Adam Boyse
Version: 1.0
Author URI: http://www.webopius.com/
*/
$qvars[] = 'paged';
return $qvars;
}

This couple of function and filter is for getting page id which is needed for building pagination in permalink-structured sites.


Step 4

At last, go to your Dashboard, create new page from Pages->Add new and name it “myanswers”, by default its slug will be myanswers. Before publishing select template for this page. In template widget you will see combobox which contains myanswers option. Select it.

After selecting myanswers option click to Publish button.


Done!

Now you can use yoursite.com/myanswers url as page which displays the loop of “the posts you commented on”. And of course not only you, every logged in user can see their own one.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: My Stream » Creating a Custom ‘The Posts I Commented On’ Loop

  • Etrimon

    Really very very helpful tip!

    Thank you!

  • http://www.cmusic.co.il/ Yakir Sitbon

    Hey.
    Why you are don’t use with Post Type or template loop (category-[slug-id])? To use by this way its wrong..

    And for the query, why don’t use by WordPress API (query_posts)?

    Thanks for this site, i really like that. :)

    Yakir.

  • John

    Useful tut, thanks to tutsplus. Of course may be there are better solutions, but it doesn’t mean that this is wrong way :-) it is easy to understand way, and i have just tested it, it works.

  • pecasso10

    some video guys are needed here.
    what’s the mater with you
    movies pleazzzzzzzzzz!

  • http://mobiland.az AzeriFire

    Very helpful post! Thank you!

  • http://shaig.muradov.org Shaig

    It is good source for wordpress developers. Thanks for information.

  • http://www.pandamonio.com Eddie

    Hi!, great Tut! I only have one question
    when I try to look into the page (my answers) I get this error:

    Fatal error: Call to undefined function twentyten_posted_on() in PATH TO MY FOLDER/loop-myanswers.php on line 33

    and on line 33:

    well how can i fix that?, again, thank for the tut! ;)

    • http://webania.net Elvin
      Author

      Hi Eddie. These codes was written for default Twentyten theme of WordPress. If you see that error, it means you use another theme, and you must change that parts of loop.
      Please look at to code, there are 2 comment lines
      /// THIS PART IS LOOP FROM TWENTYTEN, YOU CAN CHANGE IT HOWEVER YOU WANT BEGIN

      /// THIS PART IS LOOP FROM TWENTYTEN, YOU CAN CHANGE IT HOWEVER YOU WANT END

      It means that you must replace that part of code if you don’t use twentyten theme.

      • http://www.pandamonio.com Eddie

        Hi, thanks for the reply, I realize that a couple of minuts later after I posted my question hahahahaha
        Thans ;)

  • Pingback: My second tutorial in Nettuts « Webania.net – Yet another web developer blog

  • Pingback: Crear un bucle para obtener todas las entradas en las que el usuario publicó comentarios | SummArg

  • LoopGuy

    Great tut! Can I use this inside my author template to display current author’s comments? Need modification for that?