Three pieces of code to replace WordPress plugins

While WordPress plugins are really useful, you don’t need plugins always to add certain features to your themes.

Here are a few code snippets you can add to your theme files to display recent posts, random posts and recent comments.

Recent Posts

The following code will enclose the latest 10 posts in an unordered list. Change numberposts=10 to display a different number of posts.

<ul>
<?php
$myposts = get_posts('numberposts=10');
foreach($myposts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
<?php endforeach; ?>
</ul>

This uses the get_posts function to fetch the latest posts. An alternative method is to use wp_get_archives as follows:

<ul>
<?php wp_get_archives('type=postbypost&limit=10'); ?>
</ul>

Random Posts

The following code will display ten random posts. Change numberposts=10 to display a different number of posts.

<ul>
<?php
$myposts = get_posts('numberposts=10&orderby=rand');
foreach($myposts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
<?php endforeach; ?>
</ul>

Recent Comments

This is a more complex bit of code. The following has been used in the theme Statement which is the base of the theme we are running on Techtites.

<?php
global $wpdb;

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type,comment_author_url,
SUBSTRING(comment_content,1,30) AS com_excerpt
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =
$wpdb->posts.ID)
WHERE comment_approved = '1' AND comment_type = '' AND
post_password = ''
ORDER BY comment_date_gmt DESC
LIMIT 10";
$comments = $wpdb->get_results($sql);

$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {

$output .= "\n<li>".strip_tags($comment->comment_author)
.": " . "<a href=\"" . get_permalink($comment->ID) .
"#comment-" . $comment->comment_ID . "\" title=\"on " .
$comment->post_title . "\">" . strip_tags($comment->com_excerpt)
."...</a></li>";

}
$output .= "\n</ul>";
$output .= $post_HTML;

echo $output;
?>

Simply copy the code above for use, or read on for a really brief explanation.

We first define the global variable $wpdb which will allow us access to the WordPress database. $sql is the query we will run. The query will fetch the latest ten approved comments. The comment next is converted into an excerpt so that the entire comment is not displayed. The results are stored in the variable $comments.

You may want to change LIMIT 10 to display a different number of comments. You may change 30 in SUBSTRING(comment_content,1,30) to limit the number of characters in the comment excerpt.

What code do you use to replace plugins? Or, do you simply prefer using a plugin to the work?

Leave a Reply

%d bloggers like this: