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().

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.

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.

Source

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.

Source

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.

Source

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.

Source

7. Display All Subscribers In An Unordered List

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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

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

Source

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).

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.

Source

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.

Source

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.

Source

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.

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

Source

17. Custom Excerpt Length

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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

23. Insert Custom Content To Your Feed

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

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

Source

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.

Source

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.

Source

26. Breadcrumbs Without Using A Plugin

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

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

Source

27. Remove The WordPress Admin Bar

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

Source

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.

Source

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.

Source

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.

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

Source

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.

Source

32. ADDING POST THUMBNAIL TO YOUR RSS

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.

Source

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.

Source

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].

Source

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.

Source

36. WordPress Shortcode To Display Youtube Thumbnail

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

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”].

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

48. Let Authors Edit Other Posts

Let your authors edit other posts from your site.

Source

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.

Source

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.

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

Source

51. Add Featured Thumbnail Image To Admin Columns

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

Source

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.

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

Source

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.

Alternatively, you can disable revisions altogether.

Source

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.

Source

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).

Source

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.

Source

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.

Source

58. Automatic Database Repair

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

Source

59. Block External Requests

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

Source

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.

Source

61. Debug WordPress

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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

68. Protect Your .htaccess File

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

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.

Source

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.

Source

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.

Source

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/.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

81. Email Link With An Image

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

Source

82. Beautiful Blockquotes

Make your quotes stand out using this useful CSS snippet.

Source

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.

Source

84. Multiple Background Images

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

Source

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.

Source

86. Remove Smiley Borders

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

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

87. Centre Your Website

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

Source

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 :)

Source

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.

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

Source

90. Flip An Image Horizontally

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

Source

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.

Source

92. Apply A Text Shadow To Your Headings

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

Source

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.

Source

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.

Source

95. Change The Colour Of Highlighted Text

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.

Source

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.

Source

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.

Source

99. Fancy Ampersand

Style your ampersands by wrapping them inside this class.

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

Source

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.

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

And the HTML.

Source

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.

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,
Kevin

Comments (14)

  • Comment by Wayne Cochran
    Wayne Cochran
    says:

    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
    Rizwan
    says:

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

  • Comment by LeoPrince
    LeoPrince
    says:

    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
    monkeymays
    says:

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

  • Comment by Krishna Kiran
    Krishna Kiran
    says:

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

  • Comment by Kevin Muldoon
    Kevin Muldoon
    says:

    @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
    says:

    @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
    Linkon
    says:

    @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
    Linkon
    says:

    @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
    says:

    @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.

    http://wordpress.org/extend/plugins/user-role-editor/

    Install that and you’re all set :)

  • Comment by Linkon
    Linkon
    says:

    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
    TailorAds
    says:

    Great collection of very useful tips for wordpress!

    Thanks for gathering them in one place…

  • Comment by Kevin Muldoon
    Kevin Muldoon
    says:

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

  • Comment by Praveen Gowda I V
    Praveen Gowda I V
    says:

    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. :)