Codeable info

25 Useful Code Snippets for WordPress

Posted on by in WordPress Tutorials

Today I would like to share with you 25 useful code snippets for WordPress. These snippets will enhance or modify your WordPress website in some way. They are very easy to use. All you have to do is add or modify the relevant template with the code detailed in this article.

The snippets will work on any regular WordPress installation. If you are using a WordPress framework, you may need to adjust the code in some way and add the function in a different way. Every framework works in a different way so be sure to refer to the documentation for the framework you are using.

* Remember to backup your template files and/or database before performing any edits. Accidents happen! :)

1. Remove the url field from WordPress comment form

Template File to Edit: functions.php

This handy little function will remove the URL field from your comment box. Worth using if you are only getting comments from spammers.

function remove_comment_fields($fields) {
    return $fields;

2. Display comments in admin to authors own posts only

Template File to Edit: functions.php

By default, authors can see all comments when they log in to the WordPress admin area. This function restricts authors so that they can only see comments on their own articles.

function wps_get_comment_list_by_user($clauses) {
        if (is_admin()) {
                global $user_ID, $wpdb;
                $clauses['join'] = ", wp_posts";
                $clauses['where'] .= " AND wp_posts.post_author = ".$user_ID." AND wp_comments.comment_post_ID = wp_posts.ID";
        return $clauses;
if(!current_user_can('edit_others_posts')) {
add_filter('comments_clauses', 'wps_get_comment_list_by_user');

3. Temporary Maintenance

Template File to Edit: functions.php

This function can be added to your functions.php template to temporarily close down your site to visitors. Your website can still be accessed by administrators, allowing you to make the changes you need without worrying about messing up your live website.

To display your website to visitors again, simply delete the function or comment it out.

// Temp Maintenance - with http response 503 (Service Temporarily Unavailable)
// This will only block users who are NOT an administrator from viewing the website.
function wp_maintenance_mode(){
    if(!current_user_can('edit_themes') || !is_user_logged_in()){
        wp_die('Maintenance, please come back soon.', 'Maintenance - please come back soon.', array('response' => '503'));
add_action('get_header', 'wp_maintenance_mode');

4. Break Out of Frames for WordPress

Template File to Edit: functions.php

I find it unbelievable that in 2013, many people are still trying to wrap the content of an external website inside a frame. I have seen many Twitter users do this recently, which results in an ugly sharing bar at the top of your website.

To stop anyone from placing your website inside a frame, simply add this function to your functions.php template.

// Break Out of Frames for WordPress
function break_out_of_frames() {
	if (!is_preview()) {
		echo "\n<script type=\"text/javascript\">";
		echo "\n<!--";
		echo "\nif (parent.frames.length > 0) { parent.location.href = location.href; }";
		echo "\n-->";
		echo "\n</script>\n\n";
add_action('wp_head', 'break_out_of_frames');

5. Set attachment as featured image

Template File to Edit: functions.php

This function will automatically set the first image that is uploaded to a post as a featured image.

// @
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
	global $post;
	if (has_post_thumbnail()) {
		// display the featured image
		$content = the_post_thumbnail() . $content;
	} else {
		// get & set the featured image
		$attachments = get_children(array(
			'post_parent' => $post->ID, 
			'post_status' => 'inherit', 
			'post_type' => 'attachment', 
			'post_mime_type' => 'image', 
			'order' => 'ASC', 
			'orderby' => 'menu_order'
		if ($attachments) {
			foreach ($attachments as $attachment) {
				set_post_thumbnail($post->ID, $attachment->ID);
			// display the featured image
			$content = the_post_thumbnail() . $content;
	return $content;

6. Add featured images to WordPress feeds

Template File to Edit: functions.php

WordPress still does not offer the functionality to display a post’s featured image in the RSS feed. Hopefully this is something they will add in the future. Until then, you can add featured images to your feed by adding this function to your functions.php template.

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

7. Add titles to previous_post_link & next_post_link

Template File to Edit: single.php

This is a useful little snippet to use if you use previous and next links on your articles. It will enhance the links by showing the actual post name, which should encourage more people to click the links.

	$p = get_adjacent_post(false, '', true);
	if(!empty($p)) echo '<div class="prev"><a href="' . get_permalink($p->ID) . '" title="' . $p->post_title . '">' . $p->post_title . '</a></div>';
	$n = get_adjacent_post(false, '', false);
	if(!empty($n)) echo '<div class="next"><a href="' . get_permalink($n->ID) . '" title="' . $n->post_title . '">' . $n->post_title . '</a></div>'; 

8. Exclude pages from WordPress search results

Template File to Edit: functions.php

WordPress will show results from pages in regular search results. This is not always what you want, particularly if you only have a few pages. It is also common for bloggers offer a free gift to email subscribers such as an eBook; yet few actually hide these pages. A quick way to resolve this issue is to remove all pages from search results.

The function can be expanded by adding more post types to the query.

function filter_search($query) {
	if ($query->is_search) {
		$query->set('post_type', 'page');
	return $query;
add_filter('pre_get_posts', 'filter_search');

9. How to redirect to post if search results only returns one post

Template File to Edit: functions.php

WordPress will send visitors to your search.php template after a search to display a list of posts. It does this even if there is only one search result. This function addresses the issue. If there is only one search result, the user directly to the post in question.

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );

10. Set Minimal Comment Limit In WordPress

Template File to Edit: functions.php

If you are sick of poor quality comments such as “Great post”, “Thanks” or simply “:)”; you should add this function to your functions.php template. It allows you to set a minimal length for comments. Simply change the value of the $minimalCommentLength string to the minimum number of characters you require for each comment.

add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
	$minimalCommentLength = 20;
	if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
		wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
	return $commentdata;

11. Increase WordPress Memory Limit

Template File to Edit: wp-config.php

The default amount of memory in WordPress (32MB) is controlled by the php.ini file. Some plugins need more which can result in an “out of memory” error message. The amount of memory WordPress uses can be modified directly through the WordPress configuration file that is located at Simply change the value of WP_MEMORY_LIMIT to 64M, 128M etc.

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

12. Custom Class To Last Post In A Loop

Template File to Edit: functions.php

This function will add a new class to the last post in your loop. By using this function, you can style the post listed at the bottom of your home page and archives differently from the rest.

// Add a class to the last post in a loop
function last_post_class($classes){
	global $wp_query;
	if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';
	return $classes;
add_filter('post_class', 'last_post_class');

13. Hide WordPress Core Update Messages

Template File to Edit: functions.php

If you are building a WordPress website for a client or for a friend, you may want to hide the WordPress update notification in the admin area. The function below will do just that, therefore reducing the chance of someone inexperienced trying to update WordPress.

// Hide WordPress Update
function wp_hide_update() {
    remove_action('admin_notices', 'update_nag', 3);

14. Admin Only Notes

Template File to Edit: functions.php

This function will allow you to post notes to all other admin. It’s a useful snippet for reminding other admin of important information.

// Admin Note
function adminnote($atts, $content = NULL){
	if(current_user_can('edit_themes') || is_user_logged_in()){
		return '
Admin Notice
‘ . $content . ‘
add_shortcode('note', 'adminnote');
// Use [note]This will appear only to admins[/note]

15. Add Content to the End of Each RSS Post in WordPress

Template File to Edit: functions.php

Add content to the bottom of every post of your RSS feed. You could use this to discourage scrapers and add a return link back to your blog.

function feedFilter($query) {
    if ($query->is_feed) {
    return $query;
function feedContentFilter($content) {
    $content .= '<p>Extra RSS content goes here... </p>';
    return $content;

16. Allow PHP in WordPress text widgets

Template File to Edit: functions.php

The default text widget in WordPress only allows text. There are some widget plugins in the official plugin directory that allow you to add PHP inside a widget. Alternatively, you can enhance the default text widget to allow PHP by adding this function to your functions.php template.

function php_text($text) {
 if (strpos($text, '<' . '?') !== false) {
 eval('?' . '>' . $text);
 $text = ob_get_contents();
 return $text;
add_filter('widget_text', 'php_text', 99);

17. Move WordPress Admin Bar to the Bottom

Template File to Edit: functions.php

The WordPress admin bar is displayed in your header when you are logged in. You can move the bar to the button using a plugin. Alternatively, you can move the admin bar to the bottom of every page using this function.

function fb_move_admin_bar() {
    echo '
    <style type="text/css">
    body { 
    margin-top: -28px;
    padding-bottom: 28px;
    body.admin-bar #wphead {
       padding-top: 0;
    body.admin-bar #footer {
       padding-bottom: 28px;
    #wpadminbar {
        top: auto !important;
        bottom: 0;
    #wpadminbar .quicklinks .menupop ul {
        bottom: 28px;
// on backend area
add_action( 'admin_head', 'fb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'fb_move_admin_bar' );

18. Redirect your author archive link to your “About” page

Template File to Edit: functions.php

If there is only one author on your website, the authors link is kind of pointless as people can view all your posts through your archives template. This little snippet will redirect the author link to your about page instead.

add_filter( 'author_link', 'my_author_link' );
function my_author_link() {
	return home_url( 'about' );

19. Delete unused post revisions

Template File to Edit: SQL query

Revisions can take up a lot of room in your database. By running this query in your database manager (e.g. phpMyAdmin), you can delete all of your revisions.

DELETE a,b,c FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'

20. Assign all articles by Author B to Author A

Template File to Edit: SQL query

This short little SQL query allows you to transfer all posts from one author to another. A great time saver.

UPDATE wp_posts SET post_author = 'new-author-id' WHERE post_author = 'old-author-id';

21. Delete all Spam Comments

Template File to Edit: SQL query

If you have hundreds or thousands of spam comments sitting in your comment administration area, deleting all of them can be tedious. This simple SQL query deletes all spam comments at once.

DELETE FROM wp_comments WHERE comment_approved = 'spam';

22. Change Image Path Only

Template File to Edit: SQL query

Many WordPress users host their images on an external content delivery service in order to speed up the loading time of their pages and reduce the load on their current hosting solution. If you decide to do this, you need to change the image location of all of your previously uploaded images.

To do this, you need to perform two SQL queries on your database:

UPDATE wp_posts SET post_content = REPLACE (post_content, 'src="//', 'src="//');


UPDATE wp_posts SET  guid = REPLACE (guid, '', '') WHERE post_type = 'attachment';

23. Remove Settings Menus From the WordPress Dashboard

Template File to Edit: functions.php

Another code snippet for those of you are designing a website for a client or friend. This function allows you to completely remove the settings options from the WordPress admin area. This is something I recommend doing for novice users as there is a possibility they will stray onto the options page and mess something up (leaving it to you to fix it!).

/* Remove Settings and Posts Menu */
	add_action( 'admin_menu', 'my_remove_menu_pages' );
	function my_remove_menu_pages() {

24. Style First Paragraphs

Template File to Edit: functions.php

A useful snippet from Jake Rocheleau that allows you to style the first paragraph of your posts and pages differently from the rest of your content.

function first_paragraph($content){
global $post;
if ($post->post_type == "post"){
     return preg_replace('/&lt;p([^>]+)?>/', '&lt;p$1 class="first">', $content, 1); } 
else { 
       return $content; 
add_filter('the_content', 'first_paragraph');

25. Add Thumbnails in Manage Posts/Pages List

Template File to Edit: functions.php

Display the corresponding thumbnail when you browse posts and pages through your admin area.

/****** Add Thumbnails in Manage Posts/Pages List ******/
if ( !function_exists('AddThumbColumn') && function_exists('add_theme_support') ) {
    // for post and page
    add_theme_support('post-thumbnails', array( 'post', 'page' ) );
    function AddThumbColumn($cols) {
        $cols['thumbnail'] = __('Thumbnail');
        return $cols;
    function AddThumbValue($column_name, $post_id) {
            $width = (int) 35;
            $height = (int) 35;
            if ( 'thumbnail' == $column_name ) {
                // thumbnail of WP 2.9
                $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
                // image from gallery
                $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
                if ($thumbnail_id)
                    $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
                elseif ($attachments) {
                    foreach ( $attachments as $attachment_id => $attachment ) {
                        $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
                    if ( isset($thumb) && $thumb ) {
                        echo $thumb;
                    } else {
                        echo __('None');
    // for posts
    add_filter( 'manage_posts_columns', 'AddThumbColumn' );
    add_action( 'manage_posts_custom_column', 'AddThumbValue', 10, 2 );
    // for pages
    add_filter( 'manage_pages_columns', 'AddThumbColumn' );
    add_action( 'manage_pages_custom_column', 'AddThumbValue', 10, 2 );

I hope you found this list useful. If you know of any other great WordPress snippets, please feel free to share them in the comment area :)

Image Credit

Codeable info

Comments (15)

Comment by Raffo says:

Very useful… Now I’m using a snippet from yoast. I dont know it’s good or not. It’s already one package with WPSeo.

Thanks for sharing :)

Comment by Alvie says:

Wow! nice code snippets WP tips, Kevin! Thanks a lot

Comment by surya says:

interesting snippets hacksoff

Comment by Jacobus says:

Hallelujah… Your “delete all spam” code snippet is saving my day. Even though I have the usual spam plugins, I have one website which is driving me nuts because it is heavily targeted by spammers. With your code snippet I can finally delete everything in one shot. Never thought about this option so thanks Kevin!

Comment by WPcustoms says:

I grabbed a few and added it to our pool at
According credit links to your site are attached :)
keep up the good work.

Comment by XYDAC says:


I have added some of your snippets to my WordPress plugin (WordPress Ultimate CMS). Hope you don’t mind.
Do let me know in case you have any issues.

Comment by Deepak Singh says:

Useful WordPress snipplets mate!! Thanks for sharing

Comment by Nilesh says:

#24 helped me to style first paragraph of a post. Thanks for these useful snippets

Comment by Erik says:

@ Tom Jamieson

It’s not in the standard wp-config.php file. Just add it above (before) the following line:

/* That’s all, stop editing! Happy blogging. */

Comment by grails says:

Thanks, #9 is so cool. Redirecting to the result if only 1 satisfy the criteria. Makes your site friendly.

Comment by Tom Jamieson says:

Hello! I tried to implement #11 on your list, but the wp-config.php file for my site does not have that particular line in it. Any other suggestions? Thanks.

Comment by Sid@AppNina says:

This is a great list of tips and code snippets. Thanks a lot for this. I was actually looking for deleting unused post revisions…

Comment by Kevin Muldoon says:

Thanks guys. Glad you liked the article :)

Comment by Devesh says:

Lots of useful snippets here, Kevin. Fantastic work =).

Comment by NathanBWeller says:

Wow. Fantastic post Kevin! Lots of useful snippets here, can’t wait to test them all out :)

Codeable info