101 Useful WordPress Snippets

in WordPress Tutorials

Snippets are little pieces of code that you can add to your code to enhance it in some way. There are many great snippets available for WordPress that extend the functionality of your site or change what is displayed on a page.

In this article I have listed 101 snippets that I believe you will find really useful. Some of these are added directly to a specific theme template whilst many are added to your themes functions.php file in order to add additional functionality to your site. I’ve also included some wp-config.php, robots.txt and .htaccess edits together with some cool CSS classes to style your site.

As always, remember to backup your files before making any changes to your templates so that you can revert the templates if something goes wrong :)

Template Edits

The following snippets can be added directly into one of your templates such as single.php, sidebar.php or footer.php.

1. Add An Edit Link To Your Posts & Pages

I find it very useful to have an edit link on posts and pages so that I can edit articles quickly if I see a mistake or want to adjust something. You can do this by simply adding the code below to your single.php and page.php templates. Make sure the function is added within the loop. Personally, I usually add it directly after the closing H1 tag that wraps around the_title().

<?php edit_post_link(__('Edit This')); ?>

2. Display Your Latest Google+ Update On Your WordPress Blog

Add this code to any template to display the latest updates from your Google+ account (such as header.php, sidebar.php or footer.php). Make sure you replace 103329092193061943712 with your own ID.

	$googleplus = fetch_feed("http://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID
	echo '<a href="';
	echo $googleplus->items[0]['link']; echo '">';
	echo $googleplus->items[0]['summary'];
	echo '';

3. Automatically Update Your Copyright Notice

By adding this to your footer.php template you can automatically update your copyright notice in your footer every year automatically.

Copyright &copy; <?php echo the_date('Y'); ?> Website Name


4. Display Number Of Facebook Fans

Add this to any template in your site (e.g. header.php, footer.php, sidebar.php) to display the number of Facebook fans you have.

$page_id = "YOUR PAGE-ID";
$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;


5. Display All Posts With A Dropdown Menu

Add this to a template such as sidebar.php to add a dropdown menu that displays all of your posts.

<form action="<? bloginfo('url'); ?>" method="get">
<select name="page_id" id="page_id">
global $post;
$args = array( 'numberposts' => -1);
$posts = get_posts($args);
foreach( $posts as $post ) : setup_postdata($post); ?>
	<option value="<? echo $post->ID; ?>"><?php the_title(); ?></option>
<?php endforeach; ?>
<input type="submit" name="submit" value="view" />


6. Display List Of Authors In A Drop Down Menu

Add this to one of your templates for a drop down list of all of your authors.

<li id="users">
 <h2><?php _e('users:'); ?></h2>
   <form action="<?php bloginfo('url'); ?>" method="get">
     $args = array(
   	 'exclude'                 => '1',
   	 'name'                    => 'authors',
   	 'who'                     => 'authors'
   <input type="submit" name="submit" value="view" />


7. Display All Subscribers In An Unordered List

Display a list of all of your subscribers by adding this to one of your templates.

    $blogusers = get_users('blog_id=1&orderby=nicename&role=subscriber');
    foreach ($blogusers as $user) {
        echo '<li>' . $user->display_name . '</li>';


8. Display Avatars Of Logged In Users

A great little hack for those of you with member sites or open registration. This simple piece of code will display avatars of all the logged in users who are on your website. It can be added to any theme template.

       global $current_user;
       echo get_avatar( $current_user->ID, 64 );


9. Check If A Post Has More Than A Certain Number Of Image Attachments

By adding this to a template such as single.php or page.php you can do a specific action if there is more than a defined number of images. You can change the value easily from 1 to 5 or 10 etc if you want to perform an action if there are a lot of images.

$attachments = get_children(
	'post_type' => 'attachment',
	'post_mime_type' => 'image',
	'post_parent' => $post->ID
if(count($attachments) > 1) { ?>
    <!-- Do something like show a slider -->
<?php } else { ?>
    <!-- Display a single image -->
<?php } ?>


10. Display Popular Posts By Comments

Add this to a template such as sidebar.php or footer.php to display the most popular posts on your site by comments.

// kill the admin nag
if (!current_user_can('edit_users')) {
	add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');"), 2);
	add_filter('pre_option_update_core', create_function('$a', "return null;"));


11. Display Most Recently Updated Posts And Pages

Add this to one your templates to display a list of the posts and pages that were updated last.

     $today = current_time('mysql', 1);
     $howMany = 5;
     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>
foreach ($recentposts as $post) {
     if ($post->post_title == '') $post->post_title = sprintf(__('Post #%s'), $post->ID);
     echo "<li><a href='".get_permalink($post->ID)."'>";
     echo '</a></li>';
<?php endif; ?>


12. Highlight Search Terms In Search Results

To highlight the term that was searched in search results, open up search.php and replace the_title(); with echo $title;. Above this line add the following code.

	$title 	= get_the_title();
	$keys= explode(" ",$s);
	$title 	= preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong class="search-excerpt">�</strong>',

You can then style highlighted search terms as you fit by creating a class for it in the stylesheet.

strong.search-excerpt { background: yellow; }


13. Display An Author Box In Posts

Adding this to your single.php template will display an author above or below your posts (depending on where you place it in single.php).

<div class="author-box">
<div class="author-left">
<div class="author-pic"><?php echo get_avatar( get_the_author_email(), '80' ); ?></div>
<div class="author-right">
<div class="author-name"><?php the_author_meta( "display_name" ); ?></div>
<div class="author-bio"><?php the_author_meta( "user_description" ); ?></div>
<div class="author-url"><?php if (get_the_author_url()) { ?><a href="<?php the_author_url(); ?>">Visit <?php the_author(); ?>'s website</a><?php } else { } ?></div>
<div class="clear"></div>

Add this to your stylesheet in order to style the author box. I recommend changing the colours to suit the style of your WordPress theme.

.author-box { padding: 10px; background: #ccc; border: 1px solid #333;}
.author-left {float:left; width: 80px; margin: 0 15px 0 0;}
.author-right {float:left; font-size: 13px; margin: 5px 0 0 10px;}
.author-pic {border: 1px solid: #ccc;}
.author-name {font-weight:bold;}
.author-bio {padding: 5px 0 5px 0;}
.author-url {color: #555;}
.author-url a {color: #000;}
.author-url a:hover {color: #333;}
.clear {clear:both}


Functions.php Edits

The theme functions template (functions.php) is the heart of every WordPress theme. It’s where functions are defined and where certain features of WordPress can be disabled or modified.

14. Remove WordPress Version From Pages And Feeds

This code will completely remove the WordPress version from your head section and feeds so that it doesn’t show up in source code etc. A quick way of making your site more secure.

// remove version info from head and feeds
function complete_version_removal() {
	return '';
add_filter('the_generator', 'complete_version_removal');


15. Remove Nofollow Attribute From Comments

I personally would never the nofollow attribute from my comment area as it encourages spam and dilutes the internal page rank juice you pass around your own site. Though I am aware that many WordPress users remove the nofollow link to encourage comments. A quick way of doing this is by adding this to your theme functions.php file.

// remove nofollow from comments
function xwp_dofollow($str) {
	$str = preg_replace(
		'~<a ([^>]*)s*(["|']{1}w*)s*nofollow([^>]*)>~U',
		'<a ${1}${2}${3}>', $str);
	return str_replace(array(' rel=""', " rel=''"), '', $str);
remove_filter('pre_comment_content',     'wp_rel_nofollow');
add_filter   ('get_comment_author_link', 'xwp_dofollow');
add_filter   ('post_comments_link',      'xwp_dofollow');
add_filter   ('comment_reply_link',      'xwp_dofollow');
add_filter   ('comment_text',            'xwp_dofollow');


16. Display Word Count In Posts

I’ve seen a few authors begin their long articles with a notice explaining how long the article will take to read (e.g. 10-15 minutes). An alternative solution to this is to display the number of words each article has. You can do this by adding this function to your functions.php template.

// count words in posts
function word_count() {
	global $post;
	echo str_word_count($post->post_content);

You can then call the function in your single.php or page.php templates or call the function directly in the post.

<?php word_count(); ?>


17. Custom Excerpt Length

The default excerpt length is 55 words. You can make this shorter or longer by adding this to functions.php.

// custom excerpt length
function custom_excerpt_length($length) {
	return 100;
add_filter('excerpt_length', 'custom_excerpt_length');


18. Remove WordPress Update Notices

This useful function will disable the WordPress update notices from your admin area. I wouldn’t remove these notices from my own websites though I can understand the need for some website companies to do this for client websites.

// kill the admin nag
if (!current_user_can('edit_users')) {
	add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');"), 2);
	add_filter('pre_option_update_core', create_function('$a', "return null;"));


19. Allow WordPress Contributors To Upload Files

By default WordPress doesn’t allow contributors to upload files. By adding this to your functions.php template you can address this issue and let contributors upload files such as images.

if ( current_user_can('contributor') && !current_user_can('upload_files') )
	add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
	$contributor = get_role('contributor');


20. Redirect back To Referring Page After Login

If you allow registration on your website, you can add this to your functions.php file in order to redirect members back to page they logged in from.

if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
	add_filter('login_redirect', 'my_login_redirect', 10, 3);
	function my_login_redirect() {
		$location = $_SERVER['HTTP_REFERER'];


21. Style The Visual Editor

This function will let you style the visual editor that is used with your theme. A cool way of keeping the same colour scheme throughout the site.

add_filter('mce_css', 'my_editor_style');
function my_editor_style($url) {
  if ( !empty($url) )
    $url .= ',';
  // Change the path here if using sub-directory
  $url .= trailingslashit( get_stylesheet_directory_uri() ) . 'editor-style.css';
  return $url;


22. Insert Custom Content After Each Post

Most people (including myself) add content which should appear underneath posts in the single.php template. You can actually do achieve this by adding a function to your theme functions.php file.

// add custom post content
function add_post_content($content) {
	if(!is_feed() && !is_home()) {
		$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>';
	return $content;
add_filter('the_content', 'add_post_content');


23. Insert Custom Content To Your Feed

The same technique can be applied to add content into your feeds.

// add custom feed content
function add_feed_content($content) {
	if(is_feed()) {
		$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>';
	return $content;
add_filter('the_excerpt_rss', 'add_feed_content');
add_filter('the_content', 'add_feed_content');

This snippet and the previous one can be combined into the one function.

// add custom content to feeds and posts
function add_custom_content($content) {
	if(!is_home()) {
		$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>';
	return $content;
add_filter('the_excerpt_rss', 'add_custom_content');
add_filter('the_content', 'add_custom_content');


24. Remove Autolinks In Comments

If you are having problems with spammers leaving links in their comments, add this to your functions.php file to disable urls from being turned into links automatically.

remove_filter('comment_text', 'make_clickable', 9);


25. Rearrange Categories Order

This little functions.php snippet will ensure that a specific category is placed at the top of the category list at all times. Just make sure to change ‘Priority Category’ to the name of the category you want to place at the top.

$categories = get_terms('books_category');
for( $i=0; $i<sizeof($categories); $i++ ){
  if ( $categories[$i]->name == 'Priority Category' ) :
    $latest = array($categories[$i]);
if( isset($latest) )
  array_splice( $categories, 0, 0, $latest );


26. Breadcrumbs Without Using A Plugin

Add breadcrumb navigation links to a page by adding the code below to your functions.php template.

function the_breadcrumb() {
		echo '<ul id="crumbs">';
	if (!is_home()) {
		echo '<li>link</li>";
		if (is_category() || is_single()) {
			echo '<li>';
			the_category(' </li><li> ');
			if (is_single()) {
				echo "</li><li>";
				echo '</li>';
		} elseif (is_page()) {
			echo '<li>';
			echo the_title();
			echo '</li>';
	elseif (is_tag()) {single_tag_title();}
	elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
	elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
	elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
	elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
	elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
	elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
	echo '</ul>';

You can then place the breadcrumbs wherever you want by calling it in a template using the_breadcrumb() function.

<?php the_breadcrumb(); ?>


27. Remove The WordPress Admin Bar

Disable the WordPress admin bar by just adding this line of code to your functions.php file.

remove_action('init', 'wp_admin_bar_init');


28. Change WordPress Login Logo

This function will help allow you to define the login logo image (i.e. on wp-register.php and wp-login.php). Simply add this code to your functions.php template and change the background image address accordingly.

function my_custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; }
add_action('login_head', 'my_custom_login_logo');


29. Change Admin logo

To change the admin logo that is showed at the top left hand side of the page, simply add this to your functions.php template.

function custom_admin_logo() {
  echo '<style type="text/css">
          #header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; }
add_action('admin_head', 'custom_admin_logo');


30. Add Content From An External File

By adding this function to your functions.php file, you can import the content from external files into your posts and pages.

function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
  if ($file!='')
    return @file_get_contents($file);
add_shortcode( 'show_file', 'show_file_func' );

Simply use the following shortcode in your post or page to import its content.

[show_file file="http://www.yoursite.com/file345.html"]


31. How To Change The Default Gravatar On WordPress

After adding the following function to your functions.php file and uploading your gravatar image, you will be able to set a new default avatar under settings/discussion.

add_filter( 'avatar_defaults', 'newgravatar' );
function newgravatar ($avatar_defaults) {
$myavatar = get_bloginfo('template_directory') . '/images/gravataricon.gif';
$avatar_defaults[$myavatar] = "MyOwnDefaultAvatar";
return $avatar_defaults;



Most WordPress websites use th featured thumbnail image to show an image in posts and post excerpts. Unfortunately, WordPress does not show these images in the RSS feed. By adding this function to your functions.php file you can display a featured image in the RSS feed if the post has one.

function rss_post_thumbnail($content) {
  	global $post;
   	if(has_post_thumbnail($post->ID)) {
   	    	$content = '<p>' . get_the_post_thumbnail($post->ID) .
   	    	   	   '</p>' . get_the_content();
   	return $content;
add_filter('the_excerpt_rss', 'rss_post_thumbnail');
add_filter('the_content_feed', 'rss_post_thumbnail');


33. Exclude Category From Feeds

By adding this code to your functions.php file you can posts from certain categories from your feeds. This is particular useful for those who use post formats and don´t want to include quotes and links etc in your main feed.

// custom feed query
function customFeedquery($query) {
	if(is_feed()) {
		$query->set('cat','-8'); // exclude category 8
		return $query;
add_filter('pre_get_posts', 'customFeedquery');


34. How To Create A Login Form Shortcode For Your WordPress Blog

Once you’ve added this to your functions.php file, you can add a login form to any post or page by inserting the shortcode [devpress-login-form].

function devpress_login_form_shortcode() {
	if ( is_user_logged_in() )
		return '';
	return wp_login_form( array( 'echo' => false ) );
function devpress_add_shortcodes() {
	add_shortcode( 'devpress-login-form', 'devpress_login_form_shortcode' );
add_action( 'init', 'devpress_add_shortcodes' );


35. Display The Number Of Comments By Author

A great function that lets you show how many comments each author has in the comments section of your page. Once you have added the function below to your functions.php template you can display the number of comments for each author by calling author_comment_count(); anywhere inside the comments loop in your comments.php template.

function author_comment_count(){
	$oneText = '1';
	$moreText = '%';
	global $wpdb;
	$result = $wpdb->get_var('
			comment_author_email = "'.get_comment_author_email().'"'
	if($result == 1): 
		echo str_replace('%', $result, $oneText);
	elseif($result > 1): 
		echo str_replace('%', $result, $moreText);


36. WordPress Shortcode To Display Youtube Thumbnail

Insert YouTube videos into your content easily with shortcodes with this cool snippet.

    Shortcode to display youtube thumbnail on your wordpress blog.
    [youtube_thumb id="VIDEO_ID" img="0" align="left"]
    VIDEO_ID= Youtube video id
    img=0,1,2 or 3
    align= left,right,center
function wp_youtube_video_thumbnail($atts) {
          'id' => '',
          'img' => '0',
     ), $atts));
    return '';
add_shortcode('youtube_thumb', 'wp_youtube_video_thumbnail');

Once the above code has been added to your functions.php template you can insert Youtube videos easily into posts by using the shortcode youtube_thumb id e.g. [youtube_thumb id=”rNWeBVBqo2c” img=”0″ align=”center”].


37. Change The Number Of Posts Per Page In Your Admin Area

One of my favourite PHP snippets. By adding this to your functions.php template you can change the number of posts listed in your admin area. By default WordPress lists 20 posts per page though you can reduce this if you have a slow connection. By increasing it to a larger value such as 50, 100 or 200, you can perform bulk admin edits more quickly.

function my_edit_posts_per_page($posts_per_page) {
   return 5; // Change this to the number of posts per page you want.
add_filter('edit_posts_per_page', 'my_edit_posts_per_page');


38. Minimum Word Count For WordPress Posts

Force your authors to write a set number of words in their posts. Simply add this function to your functions.php file.

function minWord($content)
	global $post;
	$content = $post->post_content;
	if (str_word_count($content) < 100 ) //set this to the minimum number of words
	wp_die( __('Error: your post is below the minimum word count.') );
add_action('publish_post', 'minWord');


39. Set Maximum Title Length For WordPress Posts

Ensure authors don’t use extra long page titles by limiting the number of words that can be used. The code needs to be added to your functions.php template.

function maxWord($title)
global $post;
$title = $post->post_title;
if (str_word_count($title) >= 10 ) //set this to the maximum number of words
wp_die( __('Error: your post title is over the maximum word count.') );
add_action('publish_post', 'maxWord');


40. Delay Posts Being Published To Your RSS Feed

When this function is added to your functions.php template, you can delay your posts being published to your RSS feed. Change the $wait variable to change the number of minutes before posts are pushed to your feed.

function publish_later_on_feed($where) {
global $wpdb;
if ( is_feed() ) {
// timestamp in WP-format
$now = gmdate(&lsquo;Y-m-d H:i:s&rsquo;);
// value for wait; + device
$wait = &lsquo;10'; // integer
// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
$device = &lsquo;MINUTE&rsquo;; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
// add SQL-sytax to default $where
$where .= &rdquo; AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, &lsquo;$now&rsquo;) > $wait &ldquo;;
return $where;
add_filter(&lsquo;posts_where&rsquo;, &lsquo;publish_later_on_feed&rsquo;);


41. Redirect To Single Post Page If There Is One Post In Category Or Tag

When this piece of code is added to your functions.php file, visitors will be directed to the post itself rather than the category or tag archive if there is only one post attached to the archive.

function stf_redirect_to_post(){
    global $wp_query;
    // If there is one post on archive page
    if( is_archive() && $wp_query->post_count == 1 ){
        // Setup post data
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
} add_action('template_redirect', 'stf_redirect_to_post');


42. Add A Simple Dashboard Widget

A simple way of adding widgets to your admin dashboard. Simply add this code to your theme functions.php template for this simply text widget to be added.

// Function that output's the contents of the dashboard widget
function dashboard_widget_function() {
	echo "Hello World, this id my first Dashboard Widget!";
// Function that beeng used in the action hook
function add_dashboard_widgets() {
	wp_add_dashboard_widget('dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function');
// Register the new dashboard widget into the 'wp_dashboard_setup' action
add_action('wp_dashboard_setup', 'add_dashboard_widgets' );


43. How To List Scheduled Posts

If you schedule a lot of posts in advance, you may find this snippet useful. Simply add this code to a template such as sidebar.php or footer.php to list scheduled posts for your site.

$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();
        $do_not_duplicate = $post->ID; ?>
        <li><?php the_title(); ?></li>
    <?php endwhile;


44. Turn On More Buttons In The WordPress Visual Editor

Add additional buttons to your visual editor such as font select and horizontal rules. The code needs to be added to your functions.php template.

function add_more_buttons($buttons) {
 $buttons[] = 'hr';
 $buttons[] = 'del';
 $buttons[] = 'sub';
 $buttons[] = 'sup';
 $buttons[] = 'fontselect';
 $buttons[] = 'fontsizeselect';
 $buttons[] = 'cleanup';
 $buttons[] = 'styleselect';
 return $buttons;
add_filter("mce_buttons_3", "add_more_buttons");


45. Limit Search Results To Specific Post Types

Specify which post types are listed in your search results by adding this to your functions.php template.

function SearchFilter($query) {
    if ($query->is_search) {
return $query;


46. Only Show Authors Their Own Comments

By default authors can see all comments left on your site in the admin comment area. This function restricts comments to those from posts the author wrote.

if (!current_user_can('edit_others_posts')) {
  function author_posts_comments_only($query) {
    global $current_user;
    $query->query_vars['post_author'] = $current_user->ID;
  add_action('pre_get_comments', 'author_posts_comments_only');


47. How To Automatically Email Contributors When Their Posts Are Published

A great function for letting contributors and authors know when their articles have been published online.

function authorNotification($post_id) {
   global $wpdb;
   $post = get_post($post_id);
   $author = get_userdata($post->post_author);
   $message = "
      Hi ".$author->display_name.",
      Your post, ".$post->post_title." has just been published. Well done!
   wp_mail($author->user_email, "Your article is online", $message);
add_action('publish_post', 'authorNotification');


48. Let Authors Edit Other Posts

Let your authors edit other posts from your site.

function add_theme_caps() {
   $role = get_role( 'author' );
   $role->add_cap( 'edit_others_posts' );
add_action( 'admin_init', 'add_theme_caps');


49. Display Post Attachment Count In Admin Column

A great function to add to your theme if you add a lot of images to your posts.

add_filter('manage_posts_columns', 'posts_columns_attachment_count', 5);
add_action('manage_posts_custom_column', 'posts_custom_columns_attachment_count', 5, 2);
function posts_columns_attachment_count($defaults){
    $defaults['wps_post_attachments'] = __('Att');
    return $defaults;
function posts_custom_columns_attachment_count($column_name, $id){
	if($column_name === 'wps_post_attachments'){
	$attachments = get_children(array('post_parent'=>$id));
	$count = count($attachments);
	if($count !=0){echo $count;}


50. Display Related Posts By Current Author

Most themes show related posts underneath a post that are related to the post topic. This function lets you display related posts from the same post author.

function get_related_author_posts() {
    global $authordata, $post;
    $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post__not_in' => array( $post->ID ), 'posts_per_page' => 5 ) );
    $output = '<ul>';
    foreach ( $authors_posts as $authors_post ) {
        $output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '</a></li>';
    $output .= '</ul>';
    return $output;

After adding the above function to functions.php, make sure you add the following code to your single.php template.

<?php echo get_related_author_posts(); ?>


51. Add Featured Thumbnail Image To Admin Columns

Add this to your theme functions.php file to display post thumbnails in your admin area.

add_filter('manage_posts_columns', 'posts_columns', 5);
add_action('manage_posts_custom_column', 'posts_custom_columns', 5, 2);
function posts_columns($defaults){
    $defaults['riv_post_thumbs'] = __('Thumbs');
    return $defaults;
function posts_custom_columns($column_name, $id){
	if($column_name === 'riv_post_thumbs'){
        echo the_post_thumbnail( 'featured-thumbnail' );


52. Display The Top Commenters

There are many top commenter plugins that display the top commenters for your site in your widget areas. If you prefer to hard code this functionality into your theme you can add this to your functions.php file.

function top_comment_authors($amount = 5) {
global $wpdb;
$results = $wpdb->get_results('
    COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url
    FROM '.$wpdb->comments.'
    WHERE comment_author_email != "" AND comment_type = "" AND comment_approved = 1
    GROUP BY comment_author_email
    ORDER BY comments_count DESC, comment_author ASC
    LIMIT '.$amount
$output = "<ul>";
foreach($results as $result) {
    $output .= "<li>".$result->comment_author."</li>";
$output .= "</ul>";
echo $output;

You can then display the top commenters anywhere on your site by adding it to a template such as sidebar.php or footer.php.

<?php top_comment_authors(); ?>


WP-Config.php Edits

The wp-config.php is placed in the root of your WordPress installation (though it can be placed in the directory above for security reasons). Everyone who has installed WordPress will be familar with this file as it is where you define your WordPress database connection settings.

53. List Amount of Post Revisions

You can limit the number of revisions WordPress saves for posts and pages by setting the limit in your wp-config.php file.

# Maximum 5 revisions #
define('WP_POST_REVISIONS', 5);

Alternatively, you can disable revisions altogether.

# Disable revisions #
define('WP_POST_REVISIONS', false);


54. Empty Trash Automatically

When something is deleted in WordPress, it isn’t lost completely. It is first moved to the trash folder so that it can be recovered later if you want. By adding this code to your wp-config.php file you can automatically empty the trash after a defined number of days.

define('EMPTY_TRASH_DAYS', 5 );


55. Change How Often Posts & Pages Are Autosaved

WordPress automatically saves posts and pages every 30 seconds. This can be changed by adding this line of code to your wp-config.php file (number denotes number of seconds).

define('AUTOSAVE_INTERVAL', 30);


56. Increase Memory Limit

By default WordPress uses 32mb of memory. If you have a large website with a lot of plugins you may want to increase this by adding this to your wp-config.php file.

define('WP_MEMORY_LIMIT', '96M');


57. Enable Multi Site

In order to create a network of sites with WordPress you need to add this to your wp-config.php file.

define('WP_ALLOW_MULTISITE', true);


58. Automatic Database Repair

Automatically repair and optimise your database by adding this to your wp-config.php file.

define('WP_ALLOW_REPAIR', true);


59. Block External Requests

Stop WordPress from making external requests by adding this to your wp-config.php file.

define('WP_HTTP_BLOCK_EXTERNAL', true);


60. Override Database Blog Address and Site Address

If you have transferred your website and are unsure about how to change the website and blog URL via phpMyAdmin, you can add the following code to your wp-config.php to override the database settings. You can then change the database settings when you are logged in.

define('WP_HOME', 'http://blog.wphub.com'); // no trailing slash
define('WP_SITEURL', 'http://wpmods.com');  // no trailing slash


61. Debug WordPress

A good way of debugging your site and finding problems is to enable WP_DEBUG in your wp-config.php file.

define('WP_DEBUG', true); // debugging mode: 'true' = enable; 'false' = disable


62. Force SSL Usage

Force WordPress to use the Secure Sockets Layer (SSL) protocol to ensure your data doesn’t get tampered with. Simply add the following code to your wp-config.php file.

define('FORCE_SSL_ADMIN', true);


63. Relocate Your wp-content Folder

A great way of stopping hackers is to move your wp-content folder. This folder contains your themes, plugins, uploads and more. By moving it to another folder you can stop malicious software from damaging your website. You simply need to specify where you have moved the folder in your wp-cofig.php file.

// full local path of current directory (no trailing slash)
define('WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'].'/another-folder-or-location/wp-content'); 
// full URI of current directory (no trailing slash)
define('WP_CONTENT_URL', 'http://your-domain-name.com/another-folder-or-location/wp-content');
// full local path of current directory (no trailing slash)
define('WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'].'/another-folder-or-location/wp-content/plugins'); 
// full URI of current directory (no trailing slash)
define('WP_PLUGIN_URL', 'http://your-domain-name.com/another-folder-or-location/wp-content/plugins');


Robots.txt Edits

The robots.txt file is the first file that search engines crawlers (should) look for when they visit your website. You can use this file to control what files and folders can be indexed by the search engine bot.

64. Block wp- Folders From Search Engines

Add this to your robots.txt file to stop search engines from indexing files such as wp-login-php and wp-register.php.

Disallow: /wp-


65. Suggested Robots.txt File From WordPress

If you are unsure about what to put in your robots.txt file, you may want to try the one suggested on WordPress.org.

Sitemap: http://www.example.com/sitemap.xml
# Google Image
User-agent: Googlebot-Image
Allow: /*
# Google AdSense
User-agent: Mediapartners-Google*
# digg mirror
User-agent: duggmirror
Disallow: /
# global
User-agent: *
Disallow: /cgi-bin/
Disallow: /wp-admin/
Disallow: /wp-includes/
Disallow: /wp-content/plugins/
Disallow: /wp-content/cache/
Disallow: /wp-content/themes/
Disallow: /trackback/
Disallow: /feed/
Disallow: /comments/
Disallow: /category/*/*
Disallow: */trackback/
Disallow: */feed/
Disallow: */comments/
Disallow: /*?
Allow: /wp-content/uploads/


66. Lean Version Of Robots.txt

Jeff Starr published a leaner version of robots.txt a year ago that some of you may prefer to the one on WordPress.org.

Sitemap: http://example.com/sitemap.xml
User-agent: *
Disallow: /feed/
Disallow: /trackback/
Disallow: /wp-admin/
Disallow: /wp-content/
Disallow: /wp-includes/
Disallow: /xmlrpc.php
Disallow: /wp-


HTAccess Edits

The .htaccess file is very versatile and allows you to control permalinks, protect directories, set URL redirects and much more. Please make sure you backup your .htaccess file before making any changes to it as any mistakes in this file usually result in your site going down (if this happens simply overwrite the .htaccess file with the original version).

67. Protect Your wp-config.php File

The wp-config.php contains the information required to connect your database. Make your website more secure by adding this code to your .htaccess file in order to protect the file.

<Files wp-config.php>
order allow,deny
deny from all


68. Protect Your .htaccess File

For extra security, you can protect the .htaccess file too by adding this to the contents of .htaccess.

<Files .htaccess>
order allow,deny
deny from all

69. Only Allow Admin Access From Your IP Address

If you are concerned about unauthorised persons accessing your admin area, add this to your .htaccess file.

# my ip address only
order deny,allow
allow from MY IP ADDRESS (replace with your IP address)
deny from all


70. Disable Directory Browsing

Another great tip from WPZine is to add the following code to your .htaccess file to stop anyone from browsing your website directories.

# disable directory browsing
Options All &ndash;Indexes


71. Use .htaccess To Blacklist Users And Bots

If you know the IP address of spam bots or spammers that are spamming your website, you can block them from accessing your whole site by denying access via the .htaccess file.

order allow, deny
allow from all
deny from
deny from
deny from


72. Remove The /category/ From WordPress Category Permalink

You can add this piece of code to your .htaccess file to remove category from your URLs e.g. change www.wpmods.com/category/wordpress-themes/ to http://blog.wphub.com/wordpress-themes/.

RewriteRule ^category/(.+)$ http://www.yourblogname.com/$1 [R=301,L]


73. Prevent Hotlinking

Hotlinking can be a real pain. Commonly caused by blog scrapers and forum users, hotlinking can eat up your bandwidth and slow down your site. By showing a ‘No Hotlinking’ image to hotlinkers you can stop them from stealing your bandwidth and encourage them to stop.

This isn’t suitable for everyone though as preventing hotlinking also stops RSS readers from displaying your images. Therefore, I would only advise taking this step if you don’t show the full post in your RSS feed.

RewriteEngine On
#Replace ?mysite.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+.)?mysite.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]


74. Redirect WordPress Feeds To Feedburner

Redirect your main feed and your comment feed to Feedburner by adding this code to your .htaccess file. Make sure you change the Feedburner URLs accordingly.

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{REQUEST_URI}      ^/?(feed.*|comments.*)        [NC]
 RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC] 
 RewriteRule ^feed/?.*$          http://feeds.feedburner.com/yourfeed        [L,NC,R=302]
 RewriteRule ^comments/?.*$      http://feeds.feedburner.com/yourcommentfeed [L,NC,R=302]


75. Deny Comment Posting To Requests With No Referrer

Comment spam is a big problem for WordPress users. One way to stop this is to prevent comments from requests with no referrer as a real person will always have a referrer. Make sure you change example.com to your own domain name when you add this to your .htaccess file.

# prevent comment posting to requests with no referer
RewriteEngine On
RewriteCond %{REQUEST_URI} .wp-comments-post.php*
RewriteCond %{HTTP_REFERER} !.*example.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]


76. Help Bots Find Your Robots.txt File

Search engine crawlers should look for your robots.txt file in the root of your domain however some crawlers don’t do this, causing a lot of requests for robots.txt files. By placing this in your .htaccess file you can stop this.

<IfModule mod_rewrite.c>
 RewriteBase /
 RewriteCond %{REQUEST_URI} !^/robots.txt$ [NC]
 RewriteCond %{REQUEST_URI} robots.txt [NC]
 RewriteRule .* http://example.com/robots.txt [R=301,L]


77. Help Bots Find Your Website Favicon

A similar technique can be applied to stop bad requests for your favicon. This ensures that crawlers look for your favicon.ico file in the root of your domain.

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_URI} !^/favicon.ico$ [NC]
 RewriteCond %{REQUEST_URI} /favicon(s)?.?(gif|ico|jpe?g?|png)?$ [NC]
 RewriteRule (.*) http://example.com/favicon.ico [R=301,L]


78. Help Bots Find Your Sitemaps

Jeff star advises that bots and crawlers find it difficult to find your sitemap sometimes, even if it’s been stated in your robots.txt file. Add this to your .htaccess file to ensure that they are redirected to the correct location of your sitemap.

<IfModule mod_alias.c>
 RedirectMatch 301 /sitemap.xml$ http://example.com/sitemap.xml
 RedirectMatch 301 /sitemap.xml.gz$ http://example.com/sitemap.xml.gz


79. Simpler Login URL

A cool little .htaccess trick from Chris Coyier. This lets you change your login from www.site.com/wp-login.php or www.site.com/blog/wp-login.php to the most user friendly www.site.com/login.

RewriteRule ^login$ http://yoursite.com/wp-login.php [NC,L]


CSS Edits

All of these snippets can be added to your theme stylesheet (style.css) to improve or modify the design of your site in some way.

80. Rounded Borders Around Images

Make your image borders rounded using this CSS3 snippet.

img {  
-webkit-border-radius: 25px;  
-moz-border-radius: 25px;  
border-radius: 25px;  


81. Email Link With An Image

Add an email icon or image to all of your email links.

a[href^="mailto:"] {  
     background: url(images/email.png) no-repeat rightright top;  


82. Beautiful Blockquotes

Make your quotes stand out using this useful CSS snippet.

blockquote {  
     border-left:10px solid #ccc;  
     margin:1.5em 10px;  
     padding:.5em 10px;  
blockquote:before {  
blockquote p {  


83. Hide Logo Text With Text Indent

A lot of theme developers forget to wrap the home page logo inside a H1 tag. This code allows you to use an H1 tag for your logo but ensures that text isn’t displayed over the logo.

h1 {  
        margin:0 auto;  
        background:transparent url("images/logo.jpg") no-repeat scroll;  


84. Multiple Background Images

Multiple background images can be useful for placing images against a different background.

#multiple-images {
   background: url(image_1.png) top left no-repeat,
   url(image_2.png) bottom left no-repeat,
   url(image_3.png) bottom right no-repeat;


85. Use Background Images As List Bullets

Not happy with simple discs or bullets for your list bullets? The background-image property makes it very easy to replace boring looking buttons with stylish images.

ul {list-style: none}
ul li {
	background-image: url("path-to-your-image");
	background-repeat: none;
	background-position: 0 0.5em;


86. Remove Smiley Borders

Add this code to your stylesheet if you see a border around your smileys.

img.wp-smiley{ border:none;}

You can increase the space between text and smiley image that follows it by adding a margin to the smiley image.

margin:0 3px;

87. Centre Your Website

This wrapper will centre your website design and make sure that your text is aligned to the left by default.

   margin:0 auto;  


88. Style Category Posts With A Different Colour

You can style posts that are attached to certain categories differently by styling each category differently via your stylesheet. You simply need to append the category slug to the class category. For example, on WP Mods the category slug for the WordPress themes category is wordpress-themes. So to customise posts in that category I would add the class .category-wordpress-themes and change the styling as I saw fit.

This could be extended to add image backgrounds, rounded corners and more :)

background-color: #e9e9e9;
padding:5px 10px 5px 10px;


89. Drop Caps

Chris Coyier provides two ways of styling the first letter in a paragraph. The first method requires you to wrap the first letter within a span with the class firstcharacter.

.firstcharacter { float: left; color: #903; font-size: 75px; line-height: 60px; padding-top: 4px; padding-right: 8px; padding-left: 3px; font-family: Georgia; }

The second method doesn’t require any additional markup however it doesn’t work with IE 6, 7 or 8.

p:first-child:first-letter { float: left; color: #903; font-size: 75px; line-height: 60px; padding-top: 4px; padding-right: 8px; padding-left: 3px; font-family: Georgia; }


90. Flip An Image Horizontally

This cool trick lets you flip an image horizontally without using graphical software like Photoshop.

img {
        -moz-transform: scaleX(-1);
        -o-transform: scaleX(-1);
        -webkit-transform: scaleX(-1);
        transform: scaleX(-1);
        filter: FlipH;
        -ms-filter: "FlipH";


91. Image Loading Effect

A useful thing to add to your image class is a small image loading gif. The image will be shown for images until they are loaded. Useful for sites who post a lot of images in their content.

img {
   background: url(loader.gif) noâˆ&rsquo;repeat 50% 50%;


92. Apply A Text Shadow To Your Headings

Make your headings stand out with this cool little drop shadow trick.

.h2, .h3, .h4 {
   text-shadow: 2px 2px 4px #666;


93. Print Page Breaks

Print page breaks will separate content when the user prints a page. This could be used before the comment area so that a new page is printed for comments.



94. Prevent Line-Wrapping Of Links

Use this piece of code to ensure that links are not spanned across two lines. The code will ensure that the link will start on a new line if it is too long.

a { white-space: nowrap; }


95. Change The Colour Of Highlighted Text

::selection {
   background: #93CE52; /* Safari */
        color: #ffffff;
::-moz-selection {
   background: #93CE52; /* Firefox */
        color: #ffffff;

96. Alternate Comment Colours

WordPress assigns a class of odd or even to each comment posted on your website. This code lets you alternate the colours used in your comments and make them more presentable.

li.even	{
	list-style: none;
	background: #FFFF;
li.odd	{
	list-style: none;
	background: #F9F9F9;


97. Adjust Space Between Letters and Words

Change the spacing between letters and words by adding the letter-spacing and word-spacing properties to your header classes.

h3 {
color: #FF0000;
font-size: 24px;
letter-spacing: 0.3em;
word-spacing: 0.2em;


98. Use Pull Quotes For Improved Reading

Make articles easier to read by floating important quotes to the right or left hand side of your content. This technique is commonly used in magazines.

.pullquote {
width: 300px;
float: right;
margin: 5px;
font-family: Georgia, "Times New Roman", Times, serif;
font: italic bold #ff0000 ; }


99. Fancy Ampersand

Style your ampersands by wrapping them inside this class.

.amp {
font-family: Baskerville, 'Goudy Old Style', Palatino, 'Book Antiqua', serif;
font-style: italic;
font-weight: normal;

After adding the above class to your stylesheet, you can style your ampersands by placing the ampersand inside a span.

<span class="amp">&amp;</span>


100. CS Sticky Footer

With pages with little content sometimes the footer is displayed high up on the page. To ensure that your footer is displayed at the bottom of the page you can add this to your stylesheet.

* {margin:0;padding:0;} 
/* must declare 0 margins on everything, also for main layout components use padding, not 
vertical margins (top and bottom) to add spacing, else those margins get added to total height 
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */
html, body {height: 100%;}
#wrap {min-height: 100%;}
#main {overflow:auto;
	padding-bottom: 150px;}  /* must be same height as the footer */
#footer {position: relative;
	margin-top: -150px; /* negative value of footer height */
	height: 150px;
/*Opera Fix*/
body:before {/* thanks to Maleika (Kohoutec)*/
margin-top:-32767px;/* thank you Erik J - negate effect of float*/

This needs to be added to the head section of your page so that it displays correctly on Internet Explorer.

<!--[if !IE 7]>
	<style type="text/css">
		#wrap {display:table;height:100%}

And the HTML.

<div id="wrap">
	<div id="main">
<div id="footer">


101. Style Code In Your Posts & Pages

The <pre> and <code> tags are used frequently to display code in your posts and pages. This code will help you style your code and make it easier to follow. I’ve changed the style for pre and code tags frequently over the last few years. I currently use code that was borrowed from tutorials from Jeff Starr and Chris Coyier.

pre {
	padding: 0.1em 0.5em 0.3em 0.7em;
	border-left: 11px solid #ccc;
	margin: 1.7em 0 1.7em 0.3em;
	overflow: auto;
	width: 93%;
	line-height: 1.6em;
	white-space: pre-wrap;       /* css-3 */
	white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
	white-space: -pre-wrap;      /* Opera 4-6 */
	white-space: -o-pre-wrap;    /* Opera 7 */
        word-wrap: break-word;       /* Internet Explorer 5.5+ */
/* target IE7 and IE6 */
*:first-child+html pre {
	padding-bottom: 2em;
	overflow-y: hidden;
	overflow: visible;
	overflow-x: auto; 
* html pre,  { 
	padding-bottom: 2em;
	overflow: visible;
	overflow-x: auto;

Source 1 Source 2

I hope you found these snippets useful. Please feel free to share good snippets that I missed in the comments area. I also encourage you to subscribe to WP Mods via RSS, Twitter or Facebook to stay up to date with our latest articles.

Good luck,

Comments (14)

  • Comment by Wayne Cochran
    Wayne Cochran

    Great list of mods. Some of these I had already made, some I will most likely use, and some are already in effect thanks to plugins. This probably won’t replace any plugins I already use, as the ones that are achieving the same results for me are plugins like Yoast’s WP SEO, but this will keep me from going after a few others I had been considering loading.

  • Comment by Rizwan

    Awesome collection. i will use some of these in my blog

  • Comment by LeoPrince

    this package is so o sum ,
    but i m  disappoint ,bcus my requirement is not improve ,bcos i find that way,
    which is use in the process of convert of html to wordpress ,
    if u know that so plz help me bro,
    this is very important for me
    plz plz help dear,,,,,,,,,,,

  • Comment by monkeymays

    Great list! I never knew I could change the color of highlighted text! Thanks again =D

  • Comment by Krishna Kiran
    Krishna Kiran

    I’ve now known what are snippets.. Thanks for the great list! Loading effect and shadows are cool..

  • Comment by Kevin Muldoon
    Kevin Muldoon

     @Linkon I help WordPress users out when I can via the WPMods forums. I encourage you to drop by there if you need help with something.

  • Comment by Kevin Muldoon
    Kevin Muldoon

     @Linkon There isn’t a ‘featured image’ upload option. The ‘featured image’ link at the right hand side of the post editor simply loads up the image uploader – it works the same way as the media icon above the post editor.Once an image has been uploaded, anyone can make it featured. There is no current way to allow or disallow the ability to make a post featured.

  • Comment by Linkon

     @Kevin Muldoon Thanks a lot. Now I understand the structure. Hey Kevin, could you please add me to your facebook or google-talk account so that I can contact with u. As I’m new to wordpress I may need your help. It would be so kind of you.And never forget you’ve got a regular reader.
    gmail- [email protected]
    facebook id: linkon siddique

  • Comment by Linkon

     @Kevin Muldoon Thanks for your reply. I also use the User Role Editor plugin & it’s my favorite. But the problem is that it allows the contributor to upload all the media files. What I want is to let them only upload via the “featured image” option instead of the traditional upload/insert option in the default wp editor. hope u understand my problem.

  • Comment by Kevin Muldoon
    Kevin Muldoon

     @Linkon Thanks for the kind words. 
    By default, the contributor user role isn’t allowed to upload files. Due to this, I use the User Role Editor plugin on my websites so that I can give them this functionality.
    Install that and you’re all set :)

  • Comment by Linkon

    That’s the greatest ever article on wordpress I’ve seen. It prevents me to use lots of plugins. A millions of thanks to you. directly goes into my bookmark list. Well, I am facing a new problem with my wordpress site.In my site I prevent the contributor to upload media files. But I want them to upload only the featured image. So what is the trick in that case?? I searched a lot but find nothing related that. I badly need that. Please help me. Thanks again. 

  • Comment by TailorAds

    Great collection of very useful tips for wordpress!

    Thanks for gathering them in one place…

  • Comment by Kevin Muldoon
    Kevin Muldoon

    @Praveen Gowda I V Glad you found it useful Praveen :)

  • Comment by Praveen Gowda I V
    Praveen Gowda I V

    Hi Kevin,

    This is a wonderful collection.

    I will bookmark it and it is definitely useful for everyone who works with wordpress.

    Thanks for this great post. :)