WordPress How To: Developing a Comments.php File

Essential Lessons in Developing a Comments.php File with WordPress

WordPress Homepage

A successful WordPress website is one that fosters interaction between its readers and content producers using a well-crafted “comments.php” file. This interaction is not only the key to a website’s own, self-perpetuating success, but common user interactions helps communicate website activity and authority to search engines which specifically rank websites based on how appreciative visitors are of the content they find there.

For this reason, mastering the “comments.php” template within any WordPress theme is absolutely an essential part of creating and promoting a successful blog, magazine, or hobbyist website. Many novice WordPress users are intimidated by this and other PHP template files, especially because the average WordPress user generally downloads themes and shies away from making any major modifications to their appearance or functionality.

However, those modifications are actually exceedingly easy to make once a user has learned the basics of XHTML, CSS, PHP, WordPress variables, and the common ways to output site content, user data, and encourage communication between everyone who views the site. It all starts with an FTP client, a text editor, and a desire to learn new ways of expressing old ideas in pure, standards-acceptable code.

Step 1: Finding the Comments.php Template File on the Website’s Server

Finding the comments.php

For those new to customizing WordPress templates, it might be a bit difficult to locate exactly where the files are stored which need to be modified. Most often, WordPress is installed to a server’s root directory, allowing for it to be accessed as the site’s index page. In this case, a theme’s files (including the “comments.php” template) can be found by navigating to the following path using an FTP client or web-based file manager within the site’s control panel:

/public_html/wp-content/themes/your-selected-theme-folder/

Within this folder, an extensive list of PHP files will appear, with names like “single.php” and “style.css,” among others. The file to be edited is, obviously, named “comments.php.” That file can be opened using the FTP client’s built-in text editor, or it can be editing using a separate text editing program like Notepad in Windows, or TextEditor for users of Mac OS X.

This file is likely not blank, and a full template is probably already constructed within the file. What will ensue in the following steps is a guide to each of the variables placed within the file and how to use them to either revise the current design or create an entirely new template that better suits the needs of the website’s content producers and commenters.

Step 2: Learning How to Prevent Access to the Comments.php File

Comments.php on WordPress

Most of the templates stored within a theme are directly accessible by users and can display site content, such as pages, posts, categories, archives, and comments, dynamically. However, some templates cannot be directly accessed by users and, if users could access them, it’d be possible to execute malicious attacks on a site’s users, content, and even its database. The “comments.php” file is one template that absolutely should be accessed directly by a site’s users, whether accidentally or on purpose. WordPress employs a simply PHP statement to ensure that the file is accessed only when included into another document.

It looks like this:

< ?php if(!empty($_SERVER[‘SCRIPT_FILENAME’]) && ‘comments.php’ == basename($_SERVER[‘SCRIPT_FILENAME’])) : ? >

< ?php die(‘Whoa! This page cannot be viewed independently. If you wish to post a comment, please navigate to the entry you wish to comment on and use the included form present on that page. Sorry for the inconvenience!’); ? >

< ?php endif; ? >

< ?php if(!empty($post->post_password)) : ? > < ?php if($_COOKIE[‘wp-postpass_’ . COOKIEHASH] != $post->post_password) : ? >

< ?php endif; ? >

< ?php endif; ? >

The code above identifies whether or not the template is currently being viewed as an “included” PHP file and, if not, it prints a helpful error message to the site’s visitors. This ensures that no malicious activity occurs behind the scenes. It will also really, really annoy hackers who were hoping to find an easy way to compromise the site’s integrity. The second line ensures that an entry can actually be displayed; if it is protected by a password, the entry will not be displayed and neither will the “comments.php” template. Without this line of code at the top of the file, visitors could easily comment on an entry whose content they were not permitted to read.

It should be noted that, if this series of tags is not present in the theme’s current “comments.php” file, it should be added immediately and the file should be saved to the server before continuing. It’s never too soon to fix a potential security vulnerability.

Step 3: Recognizing the Comment Loop and Adding Variables to Customize its Appearance

Depending on how experienced someone is with the WordPress variables and their insertion into templates, they may or may not be familiar with the use of “loops” throughout these files when inserting variables and pulling user or post information out of the database. Both entries and comments have their own WordPress Loop formats, and that is the next series of PHP statements which will appear in the “comments.php” file. Within this loop, the actual comment template is constructed. This determines how each individual comment looks to the end user after it has been posted, and it’s a mix of XHTML, CSS, and PHP.

The CSS and XHTML elements of this template should already be well-known by the enterprising WordPress user who is learning to customize templates, as they’re an essential aspect of both the site’s appearance and its content as written in the WordPress Dashboard. Working with the assumption that XHTML and CSS are known quantities, here’s what a user will need to know about WordPress variables and PHP when editing or constructing a comments template.

Every variable within the comment loop is constructed as a separate PHP statement like the one which appears below:

< ?php get_variable ? >

Within the actual “comments.php” template itself, every single variable available for use starts with the “comment_” prefix ad is placed in between the opening and closing PHP tags as demonstrated above. There are several variables which can be used within this template to pull information out of the database.

< ?php comment_author(); ? > Pulls the author’s name from the database and prints it exactly how they typed it, wherever the variable is placed. Typically, this should be used as part of a link construction to send users either to the author’s website or their email address.

< ?php comment_date(); ? > Prints the date a comment was published; by default, this variable uses the date format as defined in the WordPress settings within the Dashboard administration panel. To customize the appearance of the date within comments, users can insert PHP date code variables (such as F jS Y) within the parentheses.

< ?php comment_ID(); ? > The numerical identification of the comment itself, generally in chronological order. This can be used to trail a comment permalink in order to link directly to a single comment.

< ?php comment_author_link(); ? > This variable is a sort of “all in one” construction for the comment author, as it prints his or her name and automatically links to any website or email address that was entered during the comment submission process.

< ?php comment_text(); ? > Prints the actual comment itself, surrounded in helpful < p > tags which can be customized using CSS styling code within the theme’s “style.css” stylesheet file.

< ?php comment_time(); ? > Like the date variable, this prints the exact hour and minute a comment was posted and uses the format set out in the WordPress Dashboard by default. It, too, can be customized by placing PHP date variables within the parentheses.

< ?php comment_type(); ? > This variable differentiates between traditional comments, trackback posts, and website pingbacks. This is useful for sorting interactions and displaying them separately throughout the comment template.

Step 4: Mastering the Art of the Comment Form

The next segment of the “comments.php” template is the actual comment submission form that enables the interaction most websites rely on. This form can be produced using standard XHTML “form” elements, and it’s likely already constructed in the existing template. The form elements must have certain names (name, email, url, comment) but, beyond that, it’s entirely up to the user to give them IDs, classes, and styling cues.

The one element which absolutely must be included whenever a comment form is designed and placed into the template is a conditional variable which only displays the form when commenting is “open.” Remember that WordPress allows commenting to be “closed” within the Dashboard on any entry, at any time. The entire ability comment site wide can also be disabled. And, of course, commenting does “time out” and automatically “close” after 30-90 days from the time a post was published. This conditional variable is placed before the opening XHTML “form” tag and it looks exactly like this:

< ?php if(comments_open()) : ? >

After the comment form has been completely inserted, with all four “form” elements, a submission button, and a reset button, the conditional PHP statement must be closed. If it isn’t, the entire page will be cut off immediately after any comments if the ability to comment on a post is revoked. The closing statements for this conditional PHP statement look like the example below:

< ?php else : ? >
< ?php endif; ? >

With that, the comment form is largely complete. Remember that every form element must be named according to the list above, or the information will not properly submit to the WordPress database. This will result in a long list of empty comments, as the data will be completely lost and not stored anywhere. This will also lead to angry readers who feel their voice has not been heard, and no site administrator wants to have that kind of problem on their conscience.

Step 5: Bringing Some Personality to the Process

Several years ago, WordPress acquired a small company known as Gravatar; that company was known for displaying universal user pictures which were tied to a specific email address. Those pictures could be displayed in entry comments on multiple websites, using multiple content management platforms, so long as the standard image URL structure was included in the template.

Since the acquisition of the company some time ago, WordPress has actually integrated this functionality directly into both the WordPress Dashboard and the “comments.php” template file. It’s a great way to personalize the user interaction experience by allowing every user to set a custom image that identifies them to their fellow commenters and website administrators.

Gravatar

First and foremost, this feature must be enabled in the WordPress Dashboard. Navigate to the “Settings” sidebar heading and click the link to the “Reading” administration panel. Here, you can set things like the maximum “rating” to be displayed in Gravatar images, as well as the default image and what to do with users who have no Gravatar image defined. When these settings have been perfected, save the page and return to the “comments.php” template which was edited earlier. A simple variable can be placed within the comments loop which will display either the default image, a dynamically-generated user avatar, or the actual Gravatar that a user has set for himself or herself.

The variable which displays all of these images is below:

< ?php echo get_avatar(); ? >

To learn more about adding gravatar into your WordPress site, read also: Bringing the Gravatar into WordPress Themes and Comments.

It’s a bit different from the standard variables used within the comments loop, but it works just as well. It can be customized with modifiers within the parentheses that determine the default image for non-Gravatar commenters, as well as the size of the image to be printed within comments. With that, the typical “comments.php” file has largely been mastered and well-learned. Now it’s time to dig deeper into custom designs, new ways of displaying user interactions, and innovative ways of including the standard comment submission form.

Always Check for Errors and Validate Design Standards

Finally, be sure to always check template modifications to ensure they’re working as smoothly as planned. As with any software solution based on PHP and MySQL, some edits or accidental coding mishaps will cause large errors to be printed on the entry’s static page, and users will be unable to use the commenting functions present in the template. With XHTML and CSS validation, careful attention to detail, and sound use of WordPress variables, this complication can be largely avoided.

When the page has stopped producing errors, and is displaying exactly how it’s intended to, the process is complete. It’s now time to show off the work to your users and encourage them to visit the Gravatar website, sign up, and customize their appearance within the comments. Remember that the new comments template is only as good as the users make it out to be, so be sure to explain any new features or requirements that have developed along the way.

And with that, your job is finished!