You might want to have comments displayed on different spots. For example, displaying the last x comments in a central template. This requires the latest comments or all comments on your site. This is a small solution that scans all the comments, or a certain number, and is supplied with markup.
The following code for example belongs in a template, which then serves a page in WordPress and displays the comments. Here are various possibilities and the code should be used only as a theoretical support and facilitate the SQL syntax.
The following solution displays the comments without track-and pingbacks.
global $wpdb; $max = '-1'; // -1 for all $result = ''; $sql = "SELECT c.*, p.post_title FROM $wpdb->comments c INNER JOIN $wpdb->posts p ON (c.comment_post_id = p.ID) "; $sql .= "WHERE comment_approved = '1' "; $sql .= "AND comment_type not in ('trackback', 'pingback') "; $sql .= "AND p.post_status != 'trash' "; $sql .= "ORDER BY comment_date DESC"; if ('-1' != $max) $sql .= " LIMIT 0, $max"; $results = $wpdb->get_results($sql); $templates = "\t" . '<li>%gravatar% <a href="%authorurl%">%authorname%</a> zu <a href="%posturl%#comment-%commentid%">%posttitle%</a> %commentcontent%</li>' . "\n"; foreach ($results as $row) { $tags = array( '%commentdate%', '%gravatar%', '%posttitle%', '%posturl%', '%authorurl%', '%authorname%', '%commentid%', '%commentcontent%' ); $replacements = array( $row->comment_date, get_avatar($row->comment_author_email, '30'), $row->post_title, get_permalink($row->comment_post_ID), $row->comment_author_url, $row->comment_author, $row->comment_ID, $row->comment_content ); $result .= str_replace($tags, $replacements, $templates); } if ($result) $result = '<ul>' . "\n" . $result . '</ul>' . "\n"; // output echo $result;
If you like to use it outside of WordPress, then you can use the comment feed as an alternative. Or you include wp-load.php
of the installation and you have full control of all functions of WordPress.
require('wp-load.php');
Have fun using it and we appreciate every suggestion, tips and error report in our comment area.
Comments
3 responses to “Use The Comments Of WordPress For More”
Directly querying the database is really poor form and you’re not making use of the object cache as a result.
It’d be much better to use
get_comments()
for this and then on each comment, check to see if the parent post is public (not password protected, trashed, etc.).@Alex: right, i see this also; but this is an solution for use pure sql to all comments and generate all content outside the wp-logic. This only the hard way to view comments and makes a result, i use this for a bridge to a other system, not for formating.
i do not understand it neither. You have to anyway login to the database, so anyway you will be inside wp or use wp-load.php. And when you use wp-load, you can use get_comments.