Eight Useful Code Snippets for WordPress

Last Updated on February 24, 2023 by 98 Comments

Eight Useful Code Snippets for WordPress
Blog / Tips & Tricks / Eight Useful Code Snippets for WordPress

There are few WordPress websites online that have not been modified in some way or another. The most common way of extending or modifying the functionality of a website is to install a WordPress plugin, however functions can also be added to theme files. In fact, the majority of WordPress themes contain functions that modify WordPress in some way.

Code snippets are little pieces of code that can be inserted directly into your theme files. Sometimes they contain full functions, other times they simply modify an existing function.

In this article, I would like to show you eight useful code snippets that will enhance WordPress. I have tested that all snippets are working using the current default theme Twenty Fourteen, however some functions may not work correctly if your theme has been modified a lot (particularly if it is a framework).

1. Empty Your Trash

As a failsafe, WordPress will keep a copy of all posts, pages and comments you delete; unless you specifically go into your trash folder and delete items permanently. The trash works in the same way as the Recycle Bin on the Windows operating system.

WordPress will automatically clear out your trash every thirty days, however this can be reduced by adding the following line of code to your wp-config.php file (this file is located in the root of your WordPress installation):

define ('EMPTY_TRASH_DAYS', 7);

If you want to optimize your database further so that no unnecessary items are stored in your database, you can disable the trash system altogether by adding this line of code to your wp-config.php file:

define ('EMPTY_TRASH_DAYS', 0);

Source

2. Reduce Post Revisions

The WordPress revision system saves a draft of your posts and pages each time you save an article. This feature is important to bloggers as it allows them to refer to earlier drafts and stops any work being lost in the event of a lost connection.

Unfortunately, these drafts take up a lot of room in your database as the default version of WordPress defines no limit on the number of drafts which are saved. This means that a large post that has been saved one hundred times would take up one hundred rows in your database table.

To address this issue, you can reduce the number of post revisions to a more sensible number by adding the following code to your wp-config.php file:

define( 'WP_POST_REVISIONS', 3 );

If you would prefer to disable the post revision system altogether, simply add this code to your wp-config.php file:

define( 'WP_POST_REVISIONS', false );

Source

WordPress also autosaves your posts and pages every sixty seconds. The interval in which posts are saved can be modified by adding the following code to your wp-config.php file:

define( 'AUTOSAVE_INTERVAL', 160 ); // Seconds

You can also clear out old post revision and keep excessive post revisions at bay using a database optimization plugin.

3. Move Your WP-Content Folders

The wp-content folder contains your themes, plugins and uploads. Certain plugins, such as caching plugins, also use the wp-content folder to store data.

Due to this, the wp-content folder is frequently a target for hackers, particularly those that insert malware into your theme files. You can make it difficult for people to find your wp-content directory by moving it to another area of your website.

If you want to simply move the wp-content folder to another location, you can add this code to your wp-config.php file:

* Notice the wp-content folder does not have a trailing slash

define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/newlocation/wp-content' );

If you prefer, you can define the new location using the URL:

define( 'WP_CONTENT_URL', 'http://www.yourwebsite.com/newlocation/wp-content' );

WordPress also allows you to rename your wp-content folder using:

define ('WP_CONTENT_FOLDERNAME', 'newfoldername'); 

Renakming your wp-content folder can make WordPress website even safer, however it is unfortunately not always practical to do so because many WordPress plugin developers continue to hard code “wp-content” into their plugin code. It may still be worth doing if security is a top priority, though be aware that it may require you to manually update the code of many plugins you use (and these would have to be manually updated every time you updated the plugin).

Source

4. Redirect Author Archive Link to Your About Page

The author archive link that is listed in the meta information area of a blog post links to a page that displays all previous posts by the author. Sometimes a bio is displayed at the top this page too.

If you run a single author blog, there is no need for you to link to author archives as the same posts are linked in your category and monthly archives. A better solution is to link your author archive link directly to your about page.

You can do this by adding the following code to your theme’s functions.php file:

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

Source

5. Redirect to Post If Search Results Return One Post

Whenever a search is performed, WordPress displays a list of all posts and pages that are related to the particular keyword or key phrase. The user can then click on the article they want to read.

If there is only one result, the search results page is not necessary. It makes more sense to simply redirect the visitor directly to the article in question.

You can do this by adding the following function to your theme’s functions.php file:

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 ) );
            exit;
        }
    }
}

Source

6. Exclude Pages from WordPress Search Results

The typical blog has hundreds or thousands of posts but just a few pages. These pages tend to be important areas of your website such as About and Contact; and are always clearly displayed in the header or sidebar. There is therefore less of a priority to include pages in search results as it is unlikely that visitors will be looking for them.

Removing pages from search results is also a quick way of hiding private pages from visitors. For example, your newsletter subscription page or your eBook download page.

Adding the code below to your themes’s functions.php will ensure that only posts are shown in search results:

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

7. Remove the URL Field From Your Comment Form

I recently spoke about how you can reduce WordPress comment spam. Here is another trick you can use to reduce manual comment spam: Remove the URL field. Doing this will greatly reduce the number of poor quality comments your blog receives.

To remove the URL field, all you have to do is add the following function to your theme’s functions.php file:

function remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

Source

8. Enforce a Minimum Content Length

Another annoying thing that some commenters do is leave short, pointless replies. Comments such as “Thanks”, “Great post” and “Cool”, add nothing to the discussion. If you do not want to remove the URL field from your comment form, you may want to enforce a minimum length for your comments so that short two word replies are not accepted.

You can do this by adding the following code to your theme’s functions.php file. Be sure to change the $minimalCommentLength string to the minimum number of character you desire.

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;
}

Source

I hope you have enjoyed this short list of useful code snippets for WordPress. If so, I encourage you to subscribe to Elegant Themes for updates of our latest blog posts.

Divi

Want To Build Better WordPress Websites? Start Here! 👇

Take the first step towards a better website.

Get Started
Divi
Premade Layouts

Check Out These Related Posts

Splice Video Editor: An Overview and Review

Splice Video Editor: An Overview and Review

Updated on March 10, 2023 in Tips & Tricks

Video is a valuable form of content for social media. Unfortunately, creating quality videos is usually a long process that involves moving mobile footage to a desktop app for editing. However, mobile editing is on the rise. Apps such as Splice Video Editor make it possible to efficiently create...

View Full Post
How to Use Font Awesome On Your WordPress Website

How to Use Font Awesome On Your WordPress Website

Updated on September 16, 2022 in Tips & Tricks

When given the choice between using a vector icon or a static image, it’s a good idea to go with the vector. They’re small and fast to load, and they can scale to any size without a loss of resolution. Font Awesome is a superb library of vector icons that you can use on your websites,...

View Full Post

98 Comments

  1. The one with the comment snippet. I uses the wp_die.
    Is it possible to have it at the same place as the comment.
    Instead of getting a blank page ?
    And thanks for the snippets.

  2. I was wondering about how theme upgrades would affect these kinds of changes to code? If I have wordpress and a theme with automatic updates, does that mean I need to change these settings every time?

    If I instead create a child theme with the code changes, the original theme updates won’t work? I probably have this wrong but would appreciate clarification.

    /don

    • Theme upgrades would not affect wp-config.php edits, but it would effect other snippets.

      Thankfully, the solution is easy. Most of these snippets are placed in the functions.php template. Simply copy the snippets to the new theme (or update).

      • Hi,
        sorry, I am a WP newbie, could you tell me if it is better to put the code snippet for the revision limits in the child theme or in the regular wp-config.php?

        Thanks!

  3. Just signed up, great themes! Hope you can help with this – where can I find a basic ‘comments/feedback’ form? Thanks!

    • The comments form is normally placed in the comments.php template file.

  4. Can I use this snippets also for multisite installation?

    • I’m not sure Rocco. I don’t have much experience with multisite. I imagine they would work, but I’m not sure. I’d have to test it.

  5. Thank you for any other great article. Where else may
    just anyone get that kind of info in such an ideal way of writing?
    I’ve a presentation subsequent week, and I am on the look for such info.

    • You’re welcome 🙂

  6. Nice tips. thanks

    • You’re welcome.

  7. Good tips, Kevin. I believe the first two or three points can be covered off by installing WP Optimize, which you can set to automatically run once a week to do a bit of a cleanup.

    • Definitely. I use it on one of my websites. However, it is sometimes better to make a small change to the wp-config.php file rather than install another plugin.

  8. Really, great tips!

    100 Thanks.

    • You’re welcome.

  9. Wonderful tips Kevin. Specially the thrash and revisions one. You rock !!!

    • Thanks Zakir.

  10. Excellent post Kevin. In regards to item #2, will it work on “page” revisions as well as posts? Or is there some other code that you can insert for that too?

    • Yes it covers the same thing. Post revisions refer to revisions of posts and pages 🙂

  11. Great article Kev!

    Question, is there a repository of snippets like these anywhere? like WordPress codex? or something similar?

    Thanks again for the article

    -Kraymer

    • If you search for WordPress snippets on a search engine, you should come across blogs and websites that list snippets.

      Be sure to test any snippet on a test website before applying it to your live website as the snippet may no longer function correctly (which is why I tested all snippets in this article to ensure they were working).

      The reason for this is usually because the code is old and is no longer applicable. Many snippet websites do not detail whether they tested the snippet, and if they did test it, what version of WordPress they tested it on. So be sure to test snippets beforehand.

  12. Hi Kevin. Great code snippets! Thanks for your blog post.
    One question to #3 as I just tried it and have some trouble with it.
    My website was already in place and now I moved the wp-content folder and changed the wp-config.php
    The result is: I can’t see my website anymore 🙁

    The original ftp path was http://www.mywebsite.com/wordpress/wp-content

    I thought it is a good idea to take the wp-content folder completely out of the wordpress folder and defined as follows:

    define( ‘WP_CONTENT_URL’, ‘http://www.mywebsite.com/wp-content’ );

    When you call my website in a browser it gets directly routed to the folder http://www.mywebsite.com/wordpress/

    As you see the wordpress folder and my new wp-content folder are on the same data level.

    What do you think, is it necessary that I have to leave the wp-content somewhere within the wordpress folder? Or is there any other bright idea what I could do to make my website run again?

    • I’m not sure whether this has occurred because wp-content is located in a higher directory than WordPress (difficult to say without seeing it all myself).

      I would move it to somewhere like http://www.mywebsite.com/wordpress/private and see if it works that way. If it works in a folder within the installation folder, then you’ll know installing it in a parent directory was the problem 🙂

  13. Thanks for these.
    The post revisions one is really handy for many of my clients who write and re-write blog posts all the time.
    Thanks again
    Karl

    • Yes I’ve noticed many authors have routines in which they save and re-save posts every few minutes. This is not ideal if post revisions are still unlimited.

  14. Following your suggestions, I have just added to my wp-config.php your line:
    define( ‘WP_POST_REVISIONS’, 3 );
    Then I saved the file and came back to my site.
    I do not know if revision of posts and pages will now not exceed of three, but certainly those already saved are still there.
    ¿How could I get rid of them and clear my site?
    Thank you.

  15. Thank you Kevin. Your tips are very helpful. I think your daily tips and tricks contribute a large part to be successful with websites.

    • Thanks Jerry 🙂

  16. Thanks for sharing the useful codes. Every WordPress users will like this.

    • Glad you found the article useful 🙂

    • Thanks for the tip Guarav.

  17. Instantly useful. I have grabbed a few of them to paste into my wp config file. Keep up with the quality of your posts! Thanks.

    • I’ll do my best 🙂

  18. Cool. Thanks

    • You’re welcome 🙂

  19. Love it like I Love scripts in Id! Thank you a million times over! 🙂

    • You’re welcome Wendy.

  20. FYI
    This does not work with DIVI > Move Your WP-Content Folders < Will break page builder.

    • Thanks for bringing that to our attention. I will speak to Nick about it 🙂

  21. Post revisions! Awesome! Thank you for this snippet!

    • You’re welcome Richard 🙂

  22. Excellent! I’ve been limiting autosaves on all my sites, but I’ll be implementing a few of these others as well. Thanks.

    • You’re welcome Susanna.

  23. Thank you Kevin, these snippets of code will be very useful to me and I will be using some of the, particularly the useless comments one.

    I am getting a ton of spam comments that are using my contact us form, do you have some code that can stop this?

  24. Good snippets Kelvin and I’ll definitely use remove comment url. However, what if I want to disable right click of content on my blog to limit content scrapers scraping my valued posts?

  25. And you thought it was just design!

    Great info, Kevin. You reminded of some stuff I had forgotten to do on some sites, and a couple of helpful (remove URL line on comments) new ideas.

    Thanks!

    • Glad you found it useful Jack 🙂

  26. Hey Kevin

    Is there anywhere online that has some cool/useful custom
    FIelds that we could use. Maybe another blog like this would fit that 🙂

    • Hi Jacob,

      What sort of custom fields are you thinking of?

      Kevin

  27. Great post! I always love helpful tweaks. Keep them coming! Thanks.

    • Thanks Bob. 🙂

  28. This is superb! I once attempted moving my WP_Content but struggled, you made it look so easy, I will give another go. Thanks so much!

    • It is not uncommon for me to refer back to my own tutorials to check that I am doing things correctly 🙂

  29. Thank you. This is very helpful!
    Great job ET!

    • Thanks Peter.

  30. Wow, these were awesome tips! I didn’t know about the wp-config.php file codes you mentioned; in fact, I was using a plugint o reduce the number of revisions my blog keeps! Now I can get rid of that plugin and just use the code in the config file! Awesome post, thanks guys!

    • There are a lot of plugins like that which were created for novice users. They do have a place in the plugin market; however I do think it is always better to make small changes yourself instead of installing another plugin 🙂

      • I like the idea of making the small snippet change in the code, but I always wonder what will get wiped out with any update (whether its WP, theme, or plugin)…. if it is written over, will I really remember to go back and change it!??

        • There were no changes suggested in these snippets for a plugin or of the core.

          The wp-config.php file is not updated during WordPress updates. It is also common practice to backup all theme files before upgrading. The most important file to backup is functions.php as that is where common files are placed. So when upgrading a theme, you simply copy your custom functions from the old functions.php file to the new one.

          • Great point. That’s how I do it with my own themes. 🙂

          • Also there is problem with nested comments as you might see….

          • In this case Kevin i suggest using a child theme, because the functions file inside the child are added to the one already in the main theme, you only need to put the custom functions inside the child theme functions.php . This way you won’t loose the custom code every time the thme eis updated.

  31. Really always find in your posts a lot more useful information and tricks that many sites specializing in wordpress. Simple tricks and easy to understand and implement. Thanks for sharing this invaluable info for me at least.

    • I’d love to take credit for that, but that’s coming from the top. Nick (the owner of Elegant Themes) is trying to publish lots of great tutorials for members.

      I have to agree that he is taking the blog in the right direction (granted, I’m biased). Personally, I look forward to the day where Elegant Themes is known as much for its blog as it is for its theme club 🙂

  32. Nice tips. #5, though, is probably a bad idea: “If there is only one result, the search results page is not necessary. It makes more sense to simply redirect the visitor directly to the article in question.” I disagree with this. It is very useful information for a searcher to know that there is only one page that matches the query. If the site automatically redirects to a page (which might not even be what the searcher is looking for), then the searcher might think there’s something wrong. If I were the user who experienced such behaviour, I would probably run the search again to make sure that I didn’t do something wrong. A search results page with just one result is in itself very informative feedback, before the searcher decides to click, or not, on the link to the page–you seem to assume that the one result is indeed what the searcher is looking for, but it might not be.

    Consider: what if you were to add code that redirects zero-result searches to the site home page? Equally unhelpful feedback.

    • You raise an interesting point. That is something that I had not considered.

      I think the best solution would be to simply extend the code given in number five to add a message that states something like “Your search only returned one result, therefore we have redirected you directly to the post”.

      I’m not sure how what code would be necessary to do that myself, though I imagine you would need to modify the post and/or page templates to accommodate such an event happening i.e. pass some variable to those templates.

      • One thing you could do is to modify your search results template page instead of adding a function to put a “1 result returned, you will be automatically redirected in 5 seconds…” message with some javascript on the page if only 1 result is returned. Then you have the convenience with the feedback.

  33. Do you know by chance if the top WordPress plugins (Yoast, Contact Form 7, NextGen, etc) would break if you renamed the wp-content folder? Would it make sense for someone to start of list of plugins that would or would not break if this change was made?

    • I haven’t tested it with the most downloaded plugins. My suspicion is that the problem is less likely to arise because (a) Good programmers usually adhere to standard practices, and, (b) With more people downloading the plugin, there is more chance of someone reporting it as an error.

    • Yoast does not break, that was my first test. 😉

  34. Eh Kevin the Elegant Themes blog is really becoming the place to be for all things WordPress.

    I’m not too adventurous when it comes to messing with code but “Empty Your Trash” and “Reduce Post Revisions” look nice and easy… even for me.

    Keep em coming Kevin, keep em coming.

    • Thanks Keith. I recently did it on my own blog and reduced the size of my database by 60%. That’s crazy. It’s something I should have done years ago.

  35. Great info to implement on current and future sites. But you had to know that someone was going to touch where the “Wet Paint” sign was posted.

    • LOL. It was gonna’ be me but you beat me to the paint, er punch…

      • D’oh! Me too…

  36. Thanks mate, all helps. 🙂

    • Glad you liked it 🙂

  37. Cool!

    • Seems you didn’t well read point 8 above 😉

      • It took me a second to get that John haha 🙂

  38. Thanks again for sharing some super-useful snippets – I especially like being able to redirect an author bio to an about page and minify the revisions db tables.

    You guys rock.

    • It makes you wonder why the functionality is not build directly into the WordPress core.

  39. Nice snippets collection for wordpress. A great thanks for sharing this.

    • Anytime 🙂

  40. Nice handy tips, Thanks for sharing it with us.

    • You’re welcome Ashmita.

  41. Fantastic! I am implementing some of these right away.

    • Glad you found it useful Scott 🙂

  42. Great tips! Knew some of them, but certainly going to make use of those WP-CONTENT and Search Redirect codes! Thanks Kevin!

    • You’re welcome Sietse.

  43. Thank you. This is very helpful!

    • Glad you found it useful Amy 🙂

Leave A Reply

Comments are reviewed and must adhere to our comments policy.

Get Started With Divi