• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar
  • Home
  • Projects
  • Products
  • Themes
  • Tools
  • Request for Quote

Vengala Vinay

Having 12+ Years of Experience in Software Development

  • Home
  • WordPress
  • PHP
    • Codeigniter
  • Django
  • Magento
  • Selenium
  • Server
Home » Creating Your First Custom Standard WordPress Comment Templates for Seamless WooCommerce Integrations

Creating Your First Custom Standard WordPress Comment Templates for Seamless WooCommerce Integrations

Understanding WordPress Comment Template Hierarchy

Before diving into custom templates, it’s crucial to grasp how WordPress resolves comment templates. When displaying comments, WordPress follows a specific hierarchy. It first looks for a `comments.php` file in your active theme’s root directory. If not found, it falls back to the parent theme’s `comments.php`. If still no file is found, it uses a default, hardcoded template. For WooCommerce, this hierarchy is slightly modified when viewing product pages, as WooCommerce often injects its own comment display logic, but understanding the core WordPress mechanism is foundational.

Creating a Basic `comments.php` File

Let’s start by creating a functional `comments.php` file in your theme’s root directory. This file will contain the core logic for displaying comments and the comment form. We’ll use standard WordPress template tags and functions.

Create a new file named `comments.php` in your theme’s directory (e.g., `wp-content/themes/your-theme-name/comments.php`).

Paste the following code into `comments.php`:

<?php
/**
 * The template for displaying comments.
 *
 * This file contains the closing of the "container" div and everything after.
 *
 * @link https://developer.wordpress.org/themes/template-files-section/comments-template-files/
 *
 * @package WordPress
 * @subpackage Your_Theme_Name
 * @since 1.0.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/*
 * If the current post is protected by a password and
 * the visitor has not yet entered the password we do not
 * show the comments.
 */
if ( post_password_required() ) {
	return;
}
?>

<!-- wp:separator --><hr class="wp-block-separator"><!-- /wp:separator -->

<!-- wp:template-part {"slug":"comments-list","tagName":"section"} -->
<section id="comments-list">
	<h2 class="comments-title">
		<?php
		$comment_count = get_comments_number();
		if ( '1' == $comment_count ) {
			printf( esc_html__( 'One thought on “%1$s”', 'your-text-domain' ), get_the_title() );
		} else {
			printf( esc_html( _n( '%1$s thought on “%2$s”', '%1$s thoughts on “%2$s”', $comment_count, 'your-text-domain' ) ), number_format_i18n( $comment_count ), get_the_title() );
		}
		?>
	</h2>

	<ol class="comment-list">
		<?php
		wp_list_comments( array(
			'style'      => 'ol',
			'short_ping' => true,
			'avatar_size' => 60,
		) );
		?>
	</ol><!-- .comment-list -->

	<?php
	// Are there comments to navigate through?
	if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) :
	?>
		<nav id="comment-nav-below" class="comment-navigation" role="navigation">
			<h1 class="screen-reader-text"><?php esc_html_e( 'Comment navigation', 'your-text-domain' ); ?></h1>
			<div class="nav-previous"><?php previous_comments_link( '<span class="meta-nav">&larr;</span> ' . __( 'Older Comments', 'your-text-domain' ) ); ?></div>
			<div class="nav-next"><?php next_comments_link( __( 'Newer Comments' . ' <span class="meta-nav">&rarr;</span>', 'your-text-domain' ) ); ?></div>
		</nav><!-- #comment-nav-below -->
	<?php endif; // Check for comment navigation. ?>

	<?php
	// If comments are closed and there is still a comment form, load up the comment template.
	if ( ! comments_open() && get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
	?>
		<p class="no-comments"><?php esc_html_e( 'Comments are closed.', 'your-text-domain' ); ?></p>
	<?php endif; ?>
</section><!-- #comments-list -->
<!-- /wp:template-part -->

<!-- wp:template-part {"slug":"comment-form","tagName":"section"} -->
<section id="comment-form">
	<?php
	comment_form( array(
		'title_reply_before' => '<h2 id="reply-title" class="comment-reply-title">',
		'title_reply_after'  => '</h2>',
		'comment_notes_before' => '<p class="comment-notes">' . __( 'Your email address will not be published. Required fields are marked %s', 'your-text-domain' ) . '</p>',
	) );
	?>
</section><!-- #comment-form -->

Integrating with WooCommerce Product Pages

WooCommerce typically overrides the default WordPress comment display on product pages to show reviews. However, if you want to display standard comments alongside or instead of reviews, or if you’re building a custom WooCommerce theme, you’ll need to ensure your `comments.php` is correctly loaded or hook into WooCommerce’s template system.

WooCommerce uses its own template files, often located in `wp-content/plugins/woocommerce/templates/`. For product reviews, it might use `single-product/reviews.php`. To ensure your theme’s `comments.php` is considered, you might need to:

  • Check WooCommerce Template Overrides: If you have a `woocommerce` folder in your theme (e.g., `wp-content/themes/your-theme-name/woocommerce/`), check for a `single-product.php` or related files that might be directly calling comment functions or bypassing the standard WordPress template loader.
  • Hooking into WooCommerce Actions: WooCommerce provides action hooks that allow you to inject content. The `woocommerce_after_single_product_summary` hook is a common place to add custom content, including your comment section.

Let’s demonstrate how to conditionally display your custom comment section after the WooCommerce summary, but only on product pages.

Conditional Display using WooCommerce Hooks

Add the following code to your theme’s `functions.php` file:

<?php
/**
 * Display custom comments section after WooCommerce product summary.
 */
function your_theme_display_custom_comments_on_products() {
    // Only display on single product pages and if comments are enabled for the post type.
    if ( is_product() && post_type_supports( 'product', 'comments' ) ) {
        // Load the comments template.
        // Ensure comments.php exists in your theme's root.
        locate_template( 'comments.php', true );
    }
}
add_action( 'woocommerce_after_single_product_summary', 'your_theme_display_custom_comments_on_products', 15 ); // Adjust priority as needed.

/**
 * Optionally, remove default WooCommerce reviews if you only want your custom comments.
 * This is a more advanced step and depends on your specific needs.
 */
// remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10 ); // Example: remove rating
// remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_reviews_tab', 30 ); // Example: remove reviews tab
// remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 ); // Example: remove related products
?>

In this code:

  • We define a function `your_theme_display_custom_comments_on_products`.
  • Inside the function, `is_product()` checks if the current page is a single product page.
  • `post_type_supports( ‘product’, ‘comments’ )` verifies if comments are enabled for the ‘product’ post type.
  • `locate_template( ‘comments.php’, true )` is a crucial WordPress function that finds and includes the `comments.php` template file from your theme. The `true` argument ensures that the template is loaded and executed.
  • We hook this function into `woocommerce_after_single_product_summary` with a priority of 15. You might need to adjust this priority to ensure your comments appear in the desired location relative to other WooCommerce elements like related products or reviews.
  • The commented-out lines show how you might remove default WooCommerce review actions if you intend to completely replace them with your standard comment system. Use these with caution and thorough testing.

Customizing the Comment Form

The `comment_form()` function in WordPress is highly customizable. You can modify labels, add fields, and change the submit button text. The `comments.php` example above already includes some basic customization for the reply title and notes.

To add custom fields (e.g., a phone number for a service-based product), you would typically hook into the `comment_form_default_fields` filter or use the `comment_form_after_fields` action.

Adding a Custom Field to the Comment Form

Add this to your `functions.php`:

<?php
/**
 * Add custom field to the comment form.
 */
function your_theme_add_comment_form_phone_field( $fields ) {
    // Add phone field after author field.
    $fields['phone'] = '<p class="comment-form-phone">' .
                       '<label for="phone">' . __( 'Phone Number (Optional)', 'your-text-domain' ) . '</label>' .
                       '<input id="phone" name="phone" type="text" value="" size="30" />' .
                       '</p>';
    return $fields;
}
add_filter( 'comment_form_default_fields', 'your_theme_add_comment_form_phone_field' );

/**
 * Save the custom comment field data.
 */
function your_theme_save_comment_form_phone_field( $comment_id ) {
    if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] ) != '' ) {
        $phone_number = sanitize_text_field( $_POST['phone'] );
        add_comment_meta( $comment_id, 'phone', $phone_number );
    }
}
add_action( 'comment_post', 'your_theme_save_comment_form_phone_field' );

/**
 * Display the custom comment field data in the admin area.
 */
function your_theme_display_comment_form_phone_field( $comment_array ) {
    if ( get_comment_meta( $comment_array['comment_ID'], 'phone', true ) ) {
        echo '<p><strong>' . __( 'Phone Number:', 'your-text-domain' ) . '</strong> ' . esc_html( get_comment_meta( $comment_array['comment_ID'], 'phone', true ) ) . '</p>';
    }
}
add_action( 'add_meta_boxes', 'your_theme_add_comment_form_phone_field' ); // This hook might not be ideal, consider 'edit_comment' or custom metaboxes.
// A better hook for displaying in the admin comment list might be needed, or directly in the comment edit screen.
// For simplicity, let's assume we're displaying it on the comment edit screen.
function your_theme_display_comment_meta_on_edit_screen( $comment ) {
    if ( get_comment_meta( $comment->comment_ID, 'phone', true ) ) {
        echo '<h4>' . __( 'Phone Number', 'your-text-domain' ) . '</h4>';
        echo '<p>' . esc_html( get_comment_meta( $comment->comment_ID, 'phone', true ) ) . '</p>';
    }
}
add_action( 'edit_comment', 'your_theme_display_comment_meta_on_edit_screen' );
?>

Explanation:

  • `your_theme_add_comment_form_phone_field`: This function hooks into `comment_form_default_fields` to inject our custom HTML for the phone number input field.
  • `your_theme_save_comment_form_phone_field`: This function hooks into `comment_post` to save the submitted phone number as comment meta data using `add_comment_meta()`. It’s crucial to sanitize input here.
  • `your_theme_display_comment_meta_on_edit_screen`: This function hooks into `edit_comment` to display the saved phone number when viewing or editing a comment in the WordPress admin area. Note that displaying custom comment meta on the front-end requires additional template modifications within your `comments.php` or a custom walker class.

Styling Your Custom Comments

The appearance of your comments and the comment form is controlled by CSS. You’ll need to add styles to your theme’s `style.css` file or within a dedicated CSS file enqueued by your theme.

Here are some basic CSS selectors you’ll likely need to target:

/* Comments List */
.comment-list {
    list-style: none;
    padding: 0;
    margin: 2em 0;
}

.comment-list .comment {
    margin-bottom: 2em;
    padding-bottom: 1em;
    border-bottom: 1px solid #eee;
    display: flex;
    align-items: flex-start;
}

.comment-list .avatar {
    margin-right: 1em;
    border-radius: 50%;
}

.comment-list .comment-body {
    flex: 1;
}

.comment-list .comment-author {
    font-weight: bold;
    margin-bottom: 0.5em;
}

.comment-list .comment-meta {
    font-size: 0.9em;
    color: #777;
    margin-bottom: 0.5em;
}

.comment-list .comment-content p {
    margin: 0 0 0.5em 0;
}

/* Comment Form */
.comment-form {
    margin-top: 3em;
    padding-top: 2em;
    border-top: 1px solid #eee;
}

.comment-reply-title {
    margin-bottom: 1em;
}

.comment-notes,
.comment-form-author,
.comment-form-email,
.comment-form-url,
.comment-form-phone { /* Targeting our custom field */
    margin-bottom: 1em;
}

.comment-form label {
    display: block;
    margin-bottom: 0.5em;
    font-weight: bold;
}

.comment-form input[type="text"],
.comment-form input[type="email"],
.comment-form input[type="url"],
.comment-form textarea {
    width: 100%;
    padding: 0.75em;
    border: 1px solid #ccc;
    box-sizing: border-box; /* Include padding and border in the element's total width and height */
}

.comment-form textarea {
    min-height: 120px;
}

.form-submit {
    margin-top: 1em;
}

.form-submit input[type="submit"] {
    background-color: #0073aa; /* Example color */
    color: white;
    padding: 1em 1.5em;
    border: none;
    cursor: pointer;
    border-radius: 3px;
}

.form-submit input[type="submit"]:hover {
    background-color: #005177;
}

/* WooCommerce Specific Adjustments */
/* If WooCommerce reviews are present, you might need to adjust selectors */
.woocommerce div.product div.summary .comment-list {
    /* Styles specific to comments on product pages */
}

.woocommerce div.product .comment-form {
    /* Styles specific to comment forms on product pages */
}

Advanced Diagnostics and Troubleshooting

When integrating custom comment templates, especially with plugins like WooCommerce, you might encounter issues. Here’s a systematic approach to diagnosing them:

1. Template Not Loading

Symptom: Your custom `comments.php` is ignored, and either the default WordPress comments or WooCommerce reviews are shown.

  • Check Theme Hierarchy: Ensure `comments.php` is in the root of your *active* theme. If using a child theme, it must be in the child theme’s root.
  • Parent Theme Conflict: If you’re using a child theme and `comments.php` isn’t loading, the parent theme might be overriding it. Temporarily switch to a default theme (like Twenty Twenty-Three) to see if your `comments.php` then loads. If it does, the issue is with your parent theme’s template loading logic.
  • WooCommerce Overrides: As discussed, WooCommerce might be using its own templates or hooks. Use browser developer tools (Inspect Element) to examine the HTML structure and identify which template files are being included. Look for `woocommerce/templates/single-product/reviews.php` or similar.
  • `locate_template()` Usage: If you’re using `locate_template()` in `functions.php`, ensure the path is correct and the file exists. Add `error_log()` statements around `locate_template()` calls to debug.
  • Plugin Conflicts: Temporarily deactivate all plugins except WooCommerce and your theme. If the issue resolves, reactivate plugins one by one to find the conflict.

2. Comment Form Issues

Symptom: The comment form doesn’t appear, custom fields are missing, or submitted data isn’t saved.

  • `comment_form()` Arguments: Double-check the arguments passed to `comment_form()`. Ensure you haven’t accidentally disabled the form (e.g., by setting `comment_form( array( ‘comment_field’ => false ) )`).
  • `post_type_supports(‘product’, ‘comments’)` Check: For product pages, ensure comments are actually enabled for the ‘product’ post type. Go to `WP Admin -> Settings -> Discussion` and check “Allow people to post comments on new posts” (this applies globally, but product types might have specific overrides). More granular control is often managed by custom code or plugins.
  • Custom Field Saving: Verify that your `comment_post` hook function is correctly saving meta data. Use `error_log(print_r($_POST, true));` within that function to see what data is being received. Ensure `add_comment_meta()` is called with the correct comment ID and meta key.
  • JavaScript Errors: Open your browser’s developer console (usually F12) and check for JavaScript errors, especially related to form submission or AJAX.
  • Security Nonces: The `comment_form()` function automatically includes security nonces. If these are somehow stripped or corrupted, submission will fail. This is rare unless you’re heavily modifying the form HTML manually.

3. Styling Conflicts

Symptom: Comments or the form look broken or are styled incorrectly.

  • CSS Specificity: WooCommerce often uses highly specific CSS selectors. Your theme’s CSS might not be specific enough to override WooCommerce styles. Use browser developer tools to inspect elements and identify the conflicting CSS rules. You may need to increase the specificity of your selectors (e.g., `.woocommerce div.product .comment-list` instead of just `.comment-list`).
  • Enqueueing Styles: Ensure your theme’s `style.css` is correctly enqueued. If you’re using separate CSS files, make sure they are loaded in the correct order.
  • Caching: Clear your browser cache, WordPress caching plugins, and any server-level caching (like Varnish or Redis) after making CSS changes.

4. WooCommerce Reviews vs. Standard Comments

Symptom: You see both WooCommerce reviews and standard comments, or only reviews when you expect standard comments.

  • Understanding WooCommerce Hooks: WooCommerce uses specific hooks for reviews. The default hook for reviews is often `woocommerce_after_single_product_summary` with a priority of 30. If you added your comments using `woocommerce_after_single_product_summary` with a lower priority (e.g., 15), your comments will appear before the reviews.
  • Removing Default Actions: To completely replace reviews with standard comments, you must remove the WooCommerce actions that output reviews. The example `functions.php` code shows commented-out examples like `remove_action( ‘woocommerce_after_single_product_summary’, ‘woocommerce_output_product_reviews_tab’, 30 );`. Uncomment and use these carefully.
  • Plugin Settings: Check WooCommerce settings (`WP Admin -> WooCommerce -> Settings -> Products -> Advanced`) for options related to reviews.

By following these steps, you can effectively create, integrate, and troubleshoot custom comment templates for seamless integration with WooCommerce, providing a more tailored user experience on your WordPress site.

Primary Sidebar

A little about the Author

Having 12+ Years of Experience in Software Development, Vinay is a principal software architect, senior systems engineer, and elite technical consultant. He specializes in bespoke PHP/WordPress development, high-performance Magento 2 & Shopify architectures, custom plugin/theme development from scratch, and legacy code modernization (including VB6, VB.NET, PyQt, and Crystal Reports). Known for solving complex database bottlenecks, speed optimization (Core Web Vitals), and advanced security code auditing, Vinay engineers production-ready systems designed to scale under heavy concurrent load conditions.



Chat on WhatsApp

Recent Posts

  • Go Goroutines vs. Node.js Event Loop: Scaling I/O-Bound Microservices Under High Load
  • Elixir Phoenix vs. Go Gin: Concurrency Models and Fault Tolerance Under Peak Request Volume
  • Python Celery vs. Go Channels: Distributed Task Queue Overhead and Memory Reliability
  • Scala Pekko vs. Go Goroutines: Actor Model vs. CSP for Event-Driven Reactive Systems
  • Java Loom Virtual Threads vs. Go Goroutines: Under-the-Hood Scheduler and Thread Overhead Comparison

Categories

  • apache (1)
  • Business & Monetization (390)
  • Centos (4)
  • Comparisons & Decision Making (55)
  • Debian (2)
  • Debugging & Troubleshooting (584)
  • Desktop Applications (14)
  • DevOps (7)
  • DevOps & Cloud Scaling (962)
  • Django (1)
  • Laravel (4)
  • Migration & Architecture (192)
  • Mobile Applications (24)
  • MySQL (1)
  • Performance & Optimization (806)
  • PHP (5)
  • PHP Development (21)
  • Plugins & Themes (244)
  • Programming Languages (9)
  • Python (19)
  • Ruby on Rails (1)
  • Security & Compliance (543)
  • SEO & Growth (491)
  • Server (23)
  • Ubuntu (9)
  • VB6 & VB.NET (8)
  • Web Applications & Frontend (19)
  • Web Assembly (Wasm) (2)
  • WordPress (22)
  • WordPress Plugin Development (7)
  • WordPress Theme Development (357)

Recent Posts

  • Go Goroutines vs. Node.js Event Loop: Scaling I/O-Bound Microservices Under High Load
  • Elixir Phoenix vs. Go Gin: Concurrency Models and Fault Tolerance Under Peak Request Volume
  • Python Celery vs. Go Channels: Distributed Task Queue Overhead and Memory Reliability

Top Categories

  • DevOps & Cloud Scaling (962)
  • Performance & Optimization (806)
  • Debugging & Troubleshooting (584)
  • Security & Compliance (543)
  • SEO & Growth (491)
  • Business & Monetization (390)

Our Products

  • ERP & LMS Systems (4)
  • Directories & Marketplaces (4)
  • Healthcare Portals (3)
  • Point of Sale (POS) (2)
  • E-Commerce Engines (2)

Our Services

  • E-Commerce Development (10)
  • WordPress Development (8)
  • Python & Desktop GUI (7)
  • General Consulting (7)
  • Legacy Modernization (5)
  • Mobile App Development (4)

Copyright © 2026 · Vinay Vengala