Table of Contents
step 1
Step 4
Not Found
Finish!
Home Backend Development PHP Tutorial Create a personalized loop for My Comment Posts

Create a personalized loop for My Comment Posts

Sep 02, 2023 pm 06:33 PM

Sometimes, WordPress developers may need custom loops that cannot be generated using standard loops (such as category, author, index, date, archive, taxonomy, etc.). One of them is "Posts I commented on” >". In Q&A sites it means "questions I answered", so many developers may need it. Building on this tutorial, we can create another custom loop. Let's create this section.


step 1

Go to your theme folder and create a myanswers.php file and copy and paste the following code into it:

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

We just created a template file named myanswers. It will be used to display our custom loop.


Step 2

Stay in your theme folder and create a second file called loop-myanswers.php. and paste the following code into the 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 id="Not-Found">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; ?>
Copy after login

This file is used to generate our custom loop in the template file.


Step 3

Open your theme's theme functions file (functions.php) and add this function and filter to the file:

add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars )
{
/* Plugin Name: Parameter
Plugin URI: https://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;
}
Copy after login

This pair of functions and filters is used to obtain the page ID required to build pagination in a permalink structured site.


Step 4

Finally, go to your dashboard, create new page from Pages -> Add new page and name it "myanswers", by default its slug will be myanswers. Select a template for this page before publishing. In the template widget, you will see a combo box containing the myanswers option. Select it.

Create a personalized loop for My Comment Posts

After selecting the myanswers option, click the Publish button.


Finish!

You can now use yoursite.com/myanswers url as the page that displays the "Posts you commented on" loop. Of course, not just you, every logged in user can see theirs.

The above is the detailed content of Create a personalized loop for My Comment Posts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles