Shiba

Adventures in WordPress

  • Home
  • Dog
  • Art
  • Contact
  • WordPress Articles
    • WP Plugins
    • WP Programming
    • WP Admin Panels
    • WP Theme Design
    • WP How-To
    • WP Theme Images
You are here: Home / WordPress Programming / Display WordPress Comments in a Static Web Page

Display WordPress Comments in a Static Web Page

by ShibaShake 6 Comments

Display WordPress Comments in a Static Web Page

Why would you want to link WordPress comments into a static web page?

By linking your static web pages to WordPress comments, you get to utilize all of WordPress’s existing functionalities for moderating comments as well as for detecting spam comments. You also save yourself a lot of effort from writing all the backend functions for linking with a comment database, getting gravatar pictures, and countless other comment operations that are provided for you through WordPress.

To insert WordPress comments into your static web page, there are three key operations you must perform –

  1. Read comments from a WordPress page and deliver them to your static web page.
  2. Display the WordPress comments you received in your static web page.
  3. Provide an interface for users to post new WordPress comments from your static web page.

In this article, we only focus on step 1 – reading comments from a WordPress page, packaging them up into an XML stream, and delivering that to your static web page so that they can be displayed. Steps 2 and 3 are described in detail in Spry Comment Box Code.

1. Load WordPress Function Library

First of all, load the WordPress function library into your PHP code. This requires that you have WordPress already installed at your server.

The WordPress wp-load.php file is located at the root of your WordPress blog directory.

<?php
	// Load WordPress functions
	require('wp-load.php'); 

?>

2. Read WordPress Comments

// Adapted from comments_template() in wp-includes/comment-template.php
function getWPcomments() {

global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity;

	// Reading in WordPress comments into $comments array. 
	if ( ! (is_single() || is_page() || $withcomments) )
		return;

	$req = get_option('require_name_email');
	$commenter = wp_get_current_commenter();
	extract($commenter, EXTR_SKIP);

	/** @todo Use API instead of SELECTs. */
	if ( $user_ID) {
		$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) )  ORDER BY comment_date", $post->ID, $user_ID));
	} else if ( empty($comment_author) ) {
		$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post->ID));
	} else {
		$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) ORDER BY comment_date", $post->ID, $comment_author, $comment_author_email));
	}
	return $comments;
}

The above getWPcomments() function assumes that the WordPress post or page that we want to extract our comments from is pointed to by the global variable $post.This function will read all comments from $post and return the results in an array ($comments).

Therefore, it is important that we first set the value of $post, and some of the other related global variables before running this function (shown below).

Note that this getWPcomments() function is adapted from the comments_template() function in the WordPress file wp-includes/comment-template.php.

3. Get the WordPress Page to Process

$post = get_page($_REQUEST["id"]);
$id = $post->ID;
$withcomments = true; 
$comments = getWPcomments();

Here, we assume that the WordPress page ID that we want to process is passed to our PHP file through the external id parameter. For example –

http://www.example.com/example.php?id=107

Alternatively, we can also access the WordPress page by title.



In this case,we would call our PHP file by passing it a title like so -

http://www.example.com/example.php?title=Test

Now that we have retrieved our WordPress comments, we are ready to write them out in XML format.

4. Write XML Stream

$containerName = "comment-set"; $elementName = "comment";

// XML header
$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<" . $containerName . ">\n";

$xml = display_comments($xml, $elementName, $comments);
	
// Close XML container
$xml .= "</" . $containerName . ">\n";

header("Content-type: text/xml");  
echo $xml;

In line-4 we write out the XML encoding and XML container name. In line-6 we write out each of the comments contained within the $comments array.This is achieved through the display_comments function (shown below).

In line-9 we close the XML container.

Finally in lines-11 and 12 we write out the XML stream and pass it on to the requesting function.

5. Display WordPress Comments Function

/* display_comments - Generates WordPress comments contained in $comments as XML elements. display_comments function is adapted from the WordPress file wp-content/themes/default/comments.php.
   */
function display_comments($xml, $elementName, $comments) {

if ($comments) :

	$commentcounter = 0;
	foreach ($comments as $comment) :
		$commentcounter++;

		$xml .= "<" . $elementName . ">\n";
		$xml .= "<id>comment-" . $comment->comment_ID . "</id>\n";

		$xml .= "<date>" . mysql2date( get_option('date_format'), $comment->comment_date) . "</date>\n";  

		
		// Code fragment from get_comment_author_link() and get_comment_author() in wp-includes/comment-template.php
		$xml .= "<cite><![CDATA[";
		$url    = $comment->comment_author_url;
		if ( empty($comment->comment_author) )
			$author = "Anonymous";
		else
			$author = $comment->comment_author;
		if ( empty( $url ) || 'http://' == $url )
			$xml .= $author;
		else
			$xml .= "<a href=\"" . $url . "\" rel=\"nofollow\">" . $author . "</a>";
		$xml .= "]]></cite>\n";	

		
		if(function_exists('get_avatar')) $xml .= "<avatarimg><![CDATA[" . get_avatar($comment->comment_author_email, '45') . "]]></avatarimg>\n";

		if ($comment->comment_approved == '0')
			$xml .= "<text>Your comment is awaiting moderation.</text>\n";
		else {
			$newComment = str_replace(chr(13), '<br />', $comment->comment_content, $count);
			$xml .= "<text><![CDATA[" . $newComment . "]]></text>\n";
		}
		$xml .= "</" . $elementName . ">\n";


	endforeach; /* end for each comment */

else : // this is displayed if there are no comments so far

	if ('open' == $post-> comment_status) : 
	// If comments are open, but there are no comments. 

	else : // comments are closed 
		$xml .= "<text>" . "Comments are closed." . "</text>\n";
	endif;
endif; 
return $xml;
}

Example XML Stream Generated

<br />
<?xml version="1.0" encoding="utf-8"?><br />
<comment-set><br />
<comment><br />
<id>comment-1002</id><br />
<date>July 26, 2009</date><br />
<cite><![CDATA[Test]]></cite><br />
<avatarimg><![CDATA[<img alt='' src='http://www.gravatar.com/avatar/?d=monsterid&s=45' class='avatar avatar-45 avatar-default' height='45' width='45' />]]></avatarimg><br />
<text><![CDATA[Test Text]]></text><br />
</comment><br />
</comment-set><br />

We Are Done!

Now all we have to do is pass this XML stream on to the Spry comment box within our static web page. Here is an example of what the finished product looks like. Feel free to leave me questions and comments if you should run into any errors.

Example screenshot of WordPress comments being displayed on a static web page.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Comments

  1. Shagor says

    October 17, 2014 at 12:18 pm

    hi,
    i am beginner user in wordpress. your code is very easy so … maby i will do it ..
    i have an error that’s Comments are closed. and undefined function getWPcomments() please help me . . . .

    Reply
  2. asd says

    January 14, 2013 at 6:04 pm

    hope this works out for me

    Reply
  3. Award Winning Web Design Company in Dubai says

    September 18, 2012 at 12:14 pm

    Howdy excellent blog! Does running a blog similar to
    this take a large amount of work? I have absolutely no
    expertise in coding but I had been hoping to start my own blog soon.
    Anyhow, if you have any recommendations or techniques for new blog
    owners please share. I know this is off subject however I simply wanted to
    ask. Thanks!

    Reply
    • ShibaShake says

      September 19, 2012 at 11:40 am

      In terms of work, it depends on what your goals are, topic area, audience, etc.

      As for techniques, there are many web gurus around with lots of techniques that they claim work very well. I just write about things that interest me.

      Reply
  4. ShibaShake says

    October 17, 2009 at 1:59 pm

    You can use Spry to do that as well. Just use the WordPress ‘get_posts’ command to get the 5 posts, then write it out into an XML stream. Next, read that stream into your static page using Spry.

    Should work …

    Reply
  5. Healthy girl says

    October 17, 2009 at 12:48 pm

    hum that’s nice. I am looking for something similar but i need to pull the 5 latests posts into a static page.

    Reply

Recent Posts

  • Screenshot of an example article in code view of a modified Gutenberg editor.How to Harness the Power of WordPress Gutenberg Blocks and Combine It with Legacy Free-Form Text
  • Screenshot of the Success, WordPress has been installed page.Migrating Your WordPress Website to Amazon EC2 (AWS)
  • Screenshot of WinSCP for creating a SFTP configuration.How to Set-Up SFTP on Amazon EC2 (AWS)
  • WordPress Gutenberg code view screenshot of this article.How to Prevent Gutenberg Autop from Messing Up Your Code, Shortcodes, and Scripts
  • Screenshot of the Success, WordPress has been installed page.How to Create a WordPress Website on Amazon EC2 (AWS)

Recent Comments

  • Screenshot of the Success, WordPress has been installed page.How to Create a WordPress Website on Amazon EC2 (AWS) (1)
    • Erik
      - Great article. All worked great except for this step:apt install php-mysqlChanging to this fixed it:apt install ...
  • Add Custom Taxonomy Tags to Your WordPress Permalinks (125)
    • Anthony
      - Where does this code go? Like, what exact .php file please?
  • Screenshot of an example article in code view of a modified Gutenberg editor.How to Harness the Power of WordPress Gutenberg Blocks and Combine It with Legacy Free-Form Text (1)
    • tom
      - hi,my experience was like the same, but for me as theme developer the "lazy blocks"(https://wordpress.org/plugins/lazy-blocks/) ...
  • WordPress Custom Taxonomy Input Panels (106)
    • Phil T
      - This is unnecessarily confusing. Why declare a variable with the same name as your taxonomy? Why did you choose a taxonomy ...
  • Create Pop-up Windows in Your WordPress Blog with Thickbox (57)
    • Jim Camomile
      - I have used this tutorial several times and it is one of the few simple and effective ways to add popups with dynamic content, ...

Copyright © 2025 · Genesis Skins by ShibaShake · Terms of Service · Privacy Policy ·