WordPress ⁄ Jun 3, 2009
Primary Guide for WordPress Code Snippets
No matter you are a WordPress user, theme designer or developer, you always need to make some modifications to suit your personal theme. When you customize your WordPress theme, it would be a great help to hand pick some useful classic theme code snippets for reference. At WordPress Codex, you can find and search all the information you need like tags, parameters, functions and permalink that help you learn a bit more. Step by step to follow and select the right WordPress code snippets to improve your design to be a next level.
1. Primary WordPress Code Snippets
Display Recent Posts
<?php query_posts('showposts=5'); ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>
Display Recently Updated Posts/Pages
<?php
$today = current_time('mysql', 1);
$howMany = 5; //Number of posts you want to display
if ( $recentposts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_modified_gmt < '$today' ORDER BY post_modified_gmt DESC LIMIT $howMany")):
?>
<h2><?php _e("Recent Updates"); ?></h2>
<ul>
<?php
foreach ($recentposts as $post) {
if ($post->post_title == '') $post->post_title = sprintf(__('Post #%s'), $post->ID);
echo "<li><a href='".get_permalink($post->ID)."'>";
the_title();
echo '</a></li>';
}
?>
</ul>
<?php endif; ?>
Display Recent Comments
<?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;?>
Display Top Comments
<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 10");
foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ($commentcount != 0) { ?>
<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>"><?php echo $title ?></a></li>
<?php } } ?>
Display Categories in Drop-Down Box
<form action="<?php bloginfo('url'); ?>/" method="get">
<?php
$select = wp_dropdown_categories('show_option_none=Select category&show_count=1&orderby=name&echo=0');
$select = preg_replace("#<select([^>]*)>#”, “<select$1 onchange=’return this.form.submit()’>”, $select); echo $select; ?>
<noscript><input type=”submit” value=”View” /></noscript>
</form>
Display Archives in a Drop-Down Box
<select name=\"archive-dropdown\" onChange='document.location.href=this.options[this.selectedIndex].value;’> <option value=\”\”><?php echo attribute_escape(__(’Select Month’)); ?></option> <?php wp_get_archives(’type=monthly&format=option&show_post_count=1′); ?> </select>
Display Gravatars (WordPress 2.5+ Only)
<?php if(function_exists(’get_avatar’)){ echo get_avatar($comment, ‘50?);} ?>
Display Meta Section
<ul> <?php wp_register(); ?> <li><?php wp_loginout(); ?></li> <li><a href="http://www.wordpress.org/">WordPress</a></li> <?php wp_meta(); ?> <li><a href="http://validator.w3.org/check?uri=referer">XHTML</a></li> </ul>
Display A Pages Sub-Menu In Sidebar
<?php$children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');if ($children) { ?><ul> <?php echo $children; ?>
</ul>
<?php } ?>
Display Tags Cloud
<?php wp_tag_cloud('smallest=8&largest=36&'); ?>
Dynamic Title Tags
<title><?phpif (is_home()) { echo bloginfo('name');
} elseif (is_404()) {
echo '404 Not Found';
} elseif (is_category()) {
echo 'Category:'; wp_title('');
} elseif (is_search()) {
echo 'Search Results';
} elseif ( is_day() || is_month() || is_year() ) {
echo 'Archives:'; wp_title('');
} else {
echo wp_title('');
}
?></title>
Adding Smilies To WordPress Plugins
Add the following lines to your code right before you are outputting the string that you want to contain smiles.
# global $wp_smiliessearch, $wp_smiliesreplace; # $content = preg_replace($wp_smiliessearch, $wp_smiliesreplace, $content);
Display An External RSS Feed
<?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://wpforums.com/external.php?type=RSS2', 5); ?>
Display PHP On A Single Page
Allows you to display plugins and such on a single page (replace home with the page you want it to only appear on).
<?php if ( is_home() ) { include ('file.php'); } ?>
Dynamic Copyright Year
Copyright © 2005-<?php echo date('Y'); ?> site.com
Add An Edit Link
<?php edit_post_link(’Edit this post’, ”, ”); ?>
List Scheduled Posts
<?php
$my_query = new WP_Query('post_status=future&order=DESC&showposts=5');
if ($my_query->have_posts()) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile;
}
?>
Display Random Posts From Specific Tag
This snippet will create 5 random posts from the tag “news” only.
<ul>
<?php query_posts('tag=news&showposts=5&offset=0&random=true'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; endif; ?>
</ul>
Display All Posts In Descending Order For Specific Category
<ul>
<?php global $post;
$myposts = get_posts('numberposts=-1&offset=0&category=1&order=DESC');
foreach($myposts as $post) :
?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
Display the Total Number of Posts on Your Blog
<?php $numposts = $wpdb->get_var("SELECT count(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'");
if (0 < $numposts)
$numposts = number_format($numposts);
echo $numposts.' posts.';
?>
Display An Alphabetical Tag Cloud
<?php wp_tag_cloud('smallest=3&largest=12'); ?>
Display External Feed via WordPress built-in Magpie Feed Parser
<?php
include_once(ABSPATH.WPINC.'/rss.php');
define("MAGPIE_OUTPUT_ENCODING", "UTF-8");
$feed = fetch_rss("http://domain.tld/feed/");
$limit = 10; // set the number of feed items
$items = array_slice($feed->items, 0, $limit);
if(!empty($items)) {
echo '<dl>';
foreach ($items as $item) {
echo '<dt><a href="';
$item['link'] = str_replace("&", "&", $item['link']);
$item['link'] = str_replace("&&", "&", $item['link']);
echo $item['link'].'" title="'.$item['title'].'" rel="nofollow">'.$item['title'].'</a></dt>';
if (isset($item['description'])) {
echo '<dd>'.$item['description'].'</dd>';
}
}
echo '</dl>';
}
?>
2. WordPress Check Sheet

WPCandy has create a cool WordPress Help Sheet for newbies and a Advanced WordPress Help Sheet for more in deep snippets for theme designers and developers. The sheets include from the basic like basic template file, PHP snippets to styling different categories or creating dynamic page titles. Both is PDF format that you can download and print a handy paper at desktop.
1. Graphic Rating also created a WordPress Cheat Sheet that save your WordPress theme design and develop workload.
2. DBS Website created a quick reference guide and relative encyclopedia to expedite your WordPress theme development.
3. WordPress Optimization/Cheat Sheet
4. WP Toy WordPress Theme Development Check List, another excellent check list includes WordPress general codes, stylesheets, browser compatibility, pages, standard CSS classes, validate and snippet codes. You can straightly forward to download the PDF version here.
3. Related Resources
1. The blog from In The Woods has posted a very resourceful post 9 Useful Snippets for Your WordPress Functions to deeper review of the function.php code and reveal 9 php snippets to enhance your theme.
2. WPSeek a new handy tool to search for WordPress functions, function sources, template Tags, user notes and more. It’s a pretty handy tool to handle all kinds of search requests. It’s a AJAXified WordPress code snippets search engine that you cannot miss out.
3. Display Posts by Tag Frequency by DevLounge.
4. 3 Codes for a Far Better WordPress Search Page by Pro Blog Design, the snippet enhances the search default function for example show the number of results found, highlight the search terms in results and exclude certain categories from being searched.
5. 15 Useful WordPress Tricks to Make Your Theme Even Better shared 15 great snippets that make your much better.
6. Smashing Magazine resourceful posts for WordPress designers and developers.
- 10 Killer WordPress Hacks
- 8 Useful Wordpress SQL Hacks
- 10 Useful RSS Hacks For Wordpress
- Mastering WordPress Shortcodes
7. Unraveling the Secrets of WordPress’ Comments.php File by Nettuts.
4. Further Reading

1. WordPress For Dummies (For Dummies (Computer/Tech))
2. Building a WordPress Blog People Want to Read
3. WordPress Theme Design: A complete guide to creating professional WordPress themes
« Your Social Media Network Chart – GeekChart
Custom A FeedBurner FeedFlare For Your Feed »
Do you like this post?
Subscribe free via RSS, by email, or by twitter to get updates.


One Comment, Comment or Ping
DTechGadget
Great article mate, very useful and thans for write it, bookmark this page.
November 15th, 2009 at 1:20 am
Reply to “Primary Guide for WordPress Code Snippets”