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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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

1
2
3
4
$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.

$post = get_page_by_title($_REQUEST["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

1
2
3
4
5
6
7
8
9
10
11
12
$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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* 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

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

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.

Related Articles

<< Previous Next >>

<a href="http://www.shibashake.com/wordpress-theme/wordpress-xml-import-format-comments" target="_top">WordPress XML Import Format - Comments</a>

WordPress XML Import Format - Comments

In this article we consider how to write out comments data in the WordPress XML import format. Once you do this, you can easily import the generated XML file into WordPress by using the Import functionality within your WordPress dashboard. We assume that you already have the comment data extracted in a PHP script elsewhere. The first thing...

<< Previous Next >>

<a href="http://www.shibashake.com/wordpress-theme/wordpress-comments" target="_top">WordPress Comments</a>

WordPress Comments

WordPress Comments Generate Your Own Avatars for Your WordPress Blog Unhappy with the Monsters, Wavatar, or Identicon avatars that come with WordPress? Personalize your blog comments with your own set of avatar images. Displaying WordPress Comments in a Static Web Page How to extract comments from the WordPress database and format them into...

<< Previous Next >>

<a href="http://www.shibashake.com/wordpress-theme/wordpress-page-redirect" target="_top">WordPress Page Redirect</a>

WordPress Page Redirect

There are a variety of ways to achieve a dynamic page redirect from within your WordPress theme or plugin. If you are only interested in static redirects (i.e. always redirect one page address to another), then it is most efficient to use 301 redirects directly from your web server. Unlike static redirects, dynamic WordPress redirects will allow...

<Playback Stop Play >

2 Comments

  1. 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 …

    1:59 pm on October 17th, 2009 Reply
  2. hum that’s nice. I am looking for something similar but i need to pull the 5 latests posts into a static page.

    12:48 pm on October 17th, 2009 Reply

RSS feed for comments on this post. TrackBack URL

Leave a Reply

Copyright © 2009 - All Rights Reserved. Powered by WordPress & Theme Shiba by ShibaShake. Privacy Policy
search button search button
rss