10 WordPress Code Snippets that Replace Plugin Functionality

10 WordPress Code Snippets that Replace Plugin Functionality

Here at ManageWP, we love plugins. Our Plugins of the Month series alone is proof of that.

But there’s something that we love arguably just as much – code snippets. Lightweight, transparent, and easy to implement – what’s not to love?

And whilst we do love plugins, there are plenty of occasions in which they are simply not necessary. There is little point in installing a plugin when the same effect can be achieved with a code snippet.

With that in mind, I thought I’d go in search of 10 code snippets that replicate the functionality of plugins available on the WordPress.org Repository.

Keeping Your Snippets Organized

One reason you might reasonably argue that code snippets are a little complicated to manage is the fact that you have to manually paste them into the functions.php file. Whilst doing this once or twice is not an issue, if you have more than a few, keeping tabs on them can be quite difficult. On the other hand, it is easy to keep track of the various plugins you have installed, as they are individually named and listed.

However, with the Code Snippets plugin, you can effectively have the same graphical user interface for your code snippets as you do for your plugins:

Code Snippets

Now there is no reason why your code snippets can’t be kept in just as good an order as your plugins.

With that said, let’s get onto the 10 code snippets that can replicate the functionality of WordPress plugins!

Note: If you want to test out these snippets without damaging your website, you should check out our local WordPress installation guide

1. Delete Default Widgets

Plugin: Remove Default Widgets

I struggle to understand the use for WordPress’ calendar widget. It’s fair to say that many of us will never use plenty of the default widgets. So if you want them out of the way, just use the following code snippet:

  1. // unregister all widgets
  2.  function unregister_default_widgets() {
  3.      unregister_widget('WP_Widget_Pages');
  4.      unregister_widget('WP_Widget_Calendar');
  5.      unregister_widget('WP_Widget_Archives');
  6.      unregister_widget('WP_Widget_Links');
  7.      unregister_widget('WP_Widget_Meta');
  8.      unregister_widget('WP_Widget_Search');
  9.      unregister_widget('WP_Widget_Text');
  10.      unregister_widget('WP_Widget_Categories');
  11.      unregister_widget('WP_Widget_Recent_Posts');
  12.      unregister_widget('WP_Widget_Recent_Comments');
  13.      unregister_widget('WP_Widget_RSS');
  14.      unregister_widget('WP_Widget_Tag_Cloud');
  15.      unregister_widget('WP_Nav_Menu_Widget');
  16.      unregister_widget('Twenty_Eleven_Ephemera_Widget');
  17.  }
  18.  add_action('widgets_init', 'unregister_default_widgets', 11);
// unregister all widgets
 function unregister_default_widgets() {
     unregister_widget('WP_Widget_Pages');
     unregister_widget('WP_Widget_Calendar');
     unregister_widget('WP_Widget_Archives');
     unregister_widget('WP_Widget_Links');
     unregister_widget('WP_Widget_Meta');
     unregister_widget('WP_Widget_Search');
     unregister_widget('WP_Widget_Text');
     unregister_widget('WP_Widget_Categories');
     unregister_widget('WP_Widget_Recent_Posts');
     unregister_widget('WP_Widget_Recent_Comments');
     unregister_widget('WP_Widget_RSS');
     unregister_widget('WP_Widget_Tag_Cloud');
     unregister_widget('WP_Nav_Menu_Widget');
     unregister_widget('Twenty_Eleven_Ephemera_Widget');
 }
 add_action('widgets_init', 'unregister_default_widgets', 11);

As you can probably guess, you can elect to keep any individual widget by simply deleting the line of code that references it.

Source: How to Remove Default WordPress Widgets and Clean Up Your Widgets Page

2. Remove “Generator” Meta Tag

Plugin: WP Remove Header Generator

Some consider the removal of the “generator” meta tag (which informs anyone who cares to look of what version of WordPress your site is running) to be an obvious step to increasing your site’s security. But whilst you should always keep your WordPress installation up to date (therefore making the removal of the tag pointless), that is not always practically possible (for instance, when working with a client’s site).

Removing the “generator” tag is a piece of cake – just use one liner:

  1. add_filter('the_generator', create_function('', 'return "";'));
add_filter('the_generator', create_function('', 'return "";'));

Source: 10 Tips To Optimize Your WordPress Theme

3. Redirect WordPress Feeds to Feedburner

Plugin: FD Feedburner Plugin

I have been guilty of using the above plugin in the past, but it simply isn’t necessary.

  1. add_action('template_redirect', 'ilc_rss_redirect');
  2. function ilc_rss_redirect() {
  3.     if ( is_feed() && !preg_match('/feedburner|feedvalidator/i', $_SERVER['HTTP_USER_AGENT'])){
  4.         header('Location: http://feeds.feedburner.com/yourfeedname');
  5.         header('HTTP/1.1 302 Temporary Redirect');
  6.     }
  7. }
add_action('template_redirect', 'ilc_rss_redirect');
function ilc_rss_redirect() {
	if ( is_feed() && !preg_match('/feedburner|feedvalidator/i', $_SERVER['HTTP_USER_AGENT'])){
		header('Location: http://feeds.feedburner.com/yourfeedname');
		header('HTTP/1.1 302 Temporary Redirect');
	}
}

Obviously, you should replace “yourfeedname” with your Feedburner feed name.

Source: 10 Tips To Optimize Your WordPress Theme

4. Email Contributors When Their Posts Are Published

Plugin: Edit Flow

As you will know if you read this post, I am a huge fan of the Edit Flow plugin. However, if you don’t need the extensive features that it offers, and instead are just looking for a way to automatically email contributors when their posts are published, just use this quick and easy code snippet:

  1. function wpr_authorNotification($post_id) {
  2.    $post = get_post($post_id);
  3.    $author = get_userdata($post->post_author);
  4.  
  5.    $message = "
  6.      Hi ".$author->display_name.",
  7.      Your post, ".$post->post_title." has just been published. Well done!
  8.   ";
  9.    wp_mail($author->user_email, "Your article is online", $message);
  10. }
  11. add_action('publish_post', 'wpr_authorNotification');
function wpr_authorNotification($post_id) {
   $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', 'wpr_authorNotification');

Source: How to automatically email contributors when their posts are published

5. Open All Links in New Windows

Plugin: Open External Links in a New Window

I am personally not a fan of opening links in new windows – I think it should be left for the user to decide, as I explained in this post. But I’m not one to judge, so if you want to do it, use this simple code snippet:

  1. function autoblank($text) {
  2.     $return = str_replace('<a', '
function autoblank($text) {
	$return = str_replace('<a', '

One thing I should add is that the above HTML is not XHTML strict compliant. If you do want to be compliant, you should use the plugin.

Source: Add target=”_blank” on All Links

6. Add Extra Contact Methods to User Profiles

Plugin: Extra User Details

WordPress is still living in the stone age with its contact forms in the User Profile section (AIM? Yahoo IM?). Fortunately, you can add more current contact methods with this simple code snippet:

  1. add_filter('user_contactmethods', 'my_user_contactmethods');
  2.  
  3. function my_user_contactmethods($user_contactmethods){
  4.  
  5.   $user_contactmethods['twitter'] = 'Twitter Username';
  6.   $user_contactmethods['facebook'] = 'Facebook Username';
  7.  
  8.   return $user_contactmethods;
  9. }
add_filter('user_contactmethods', 'my_user_contactmethods');

function my_user_contactmethods($user_contactmethods){

  $user_contactmethods['twitter'] = 'Twitter Username';
  $user_contactmethods['facebook'] = 'Facebook Username';

  return $user_contactmethods;
}

As you can see, each new contact method just needs a name and a label.

Source: Quick Tip: Add Extra Contact Methods to User Profiles

7. Change Login Logo

Plugin: Login Logo

If you want to add a bit of individuality to your site’s login page, why not change the logo? Just use this code snippet:

  1. add_action( 'login_head', 'ilc_custom_login');
  2. function ilc_custom_login() {
  3.     echo '
add_action( 'login_head', 'ilc_custom_login');
function ilc_custom_login() {
	echo '
  1. <script type="text/javascript">// <![CDATA[
  2. window.onload = function(){document.getElementById("login").getElementsByTagName("a")[0].href = "'. home_url() . '";document.getElementById("login").getElementsByTagName("a")[0].title = "Go to site";}
  3. // ]]></script>'; }
<script type="text/javascript">// <![CDATA[
window.onload = function(){document.getElementById("login").getElementsByTagName("a")[0].href = "'. home_url() . '";document.getElementById("login").getElementsByTagName("a")[0].title = "Go to site";}
// ]]></script>'; }

Just adjust the path and name of the image to suit, and you’re done! Also, clicking on the logo will now direct a user to your homepage, rather than WordPress.org.

You can also change the WordPress login URL

Source: 10 Tips To Optimize Your WordPress Theme

8. Display Messages on the Dashboard

Plugin: Easy Admin Notification

If for whatever reason you want to display a notification or error message on the Dashboard, just use this simple code snippet:

  1. function showMessage($message, $errormsg = false){
  2.     if ($errormsg) {
  3.         echo '
function showMessage($message, $errormsg = false){
	if ($errormsg) {
		echo '
‘; } else { echo ‘

‘; } echo “$message

“; } function showAdminMessages() { showMessage(“YOUR MESSAGE HERE”, true); if (user_can(‘manage_options’) { showMessage(“Hello admins!”); } } add_action(‘admin_notices’, ‘showAdminMessages’);

Source: Super Useful WordPress Action Hooks and Filters

9. Maintenance Mode

Plugin: Maintenance Mode

If you need a quick and easy way of locking your site to non-admin users, just use this code snippet:

  1. function maintenace_mode() {
  2. if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
  3. die('YOUR MESSAGE');
  4. }
  5. }
  6. add_action('get_header', 'maintenace_mode');
function maintenace_mode() {
if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
die('YOUR MESSAGE');
}
}
add_action('get_header', 'maintenace_mode');

This will present a blank page with your chosen message.

Source: 20 WordPress Code Snippets for Constructive Web Developers

10. Add a Favicon

Plugin: All In One Favicon

Adding a favicon to your WordPress site really does not warrant a plugin. Instead, just use this extremely simple code snippet:

  1. add_action( 'wp_head', 'ilc_favicon');
  2. function ilc_favicon(){
  3.     echo "      <link href="" . get_stylesheet_directory_uri() . "/favicon.ico" rel="shortcut icon" />" . "\n";
  4. }
add_action( 'wp_head', 'ilc_favicon');
function ilc_favicon(){
	echo "		<link href="" . get_stylesheet_directory_uri() . "/favicon.ico" rel="shortcut icon" />" . "\n";
}

Once you have installed and activated the code snippet in the Code Snippets plugin, all you need to do is upload your favicon.ico file to the root directory of your active theme.

Source: 10 Tips To Optimize Your WordPress Theme

Creative Commons image courtesy of ruiwen

ManageWP
Are You Spending Valuable Time Managing Your WordPress Websites?

Over 70,000 users depend on ManageWP to save them time and trouble by managing all of their sites from one central location.

12 Comments

Join The Discussion

12 Comments

  1. Tom says:

    I'm using http://www.snip2code.com to collect snippet. Do you think that this kind of services can be useful?

  2. Nilesh says:

    I was looking for a email notification filter for contributors to notify them when a post get published and found your snippets. Thanks for sharing this.

  3. Dave says:

    Not sure if this the place ask this but here goes. I am new to wordpress and trying to change the login logo (#7). I am using wp3.5 I have found the functions.php and pasted the code in at the top of the page but I get an Fatal error: Call to undefined function add_action() in …/wp-includes/functions.php on line 8. No matter where I paste the code in functions.php I get the same message just with a different line #. Could you please advise a newbie what I am doing wrong.

    • Shea Bunge says:

      Hi, the problem is the you're pasting the code in the wrong place – it should go in the <code>functions.php</code> in your <em>theme's</em> folder, not in wp-includes. You can go to <em>Themes &gt; Editor</em> in your dashboard and select functions.php from the side menu. You may also be interested in <a href="http://wordpress.org/extend/plugins/code-snippets&quot; rel="nofollow">this plugin</a>

      • Dave says:

        Hi Shea, Thanks for your help and assistance it is now working a treat and I have learned so much more about WordPress. I have also downloaded and installed code snippets so hopefully no problems in the future. Once again many thanks.

  4. eRock says:

    Hi! Regarding #8, how would I write the code so the user can dismiss any warning messages by clicking a close button? Thanks!

    • Tom Ewer says:

      I'm afraid you've asked a question that surpasses my technical ability 😉

      I'm sure you could get an answer over at the WordPress forums though.

    • bungeshea says:

      You could try the following code:

      <code><pre>
      /* Display a notice that can be dismissed */
      add_action('admin_notices', 'example_admin_notice');
      function example_admin_notice() {
      global $current_user ;
      $user_id = $current_user-&gt;ID;
      /* Check that the user hasn't already clicked to ignore the message */
      if ( ! get_user_meta($user_id, 'example_ignore_notice') ) {
      echo '&lt;div class=&quot;updated&quot;&gt;&lt;p&gt;';
      printf(__('This is an annoying nag message. Why do people make these? | &lt;a href=&quot;%1$s&quot;&gt;Hide Notice&lt;/a&gt;'), '?example_nag_ignore=0');
      echo &quot;&lt;/p&gt;&lt;/div&gt;&quot;;
      }
      }
      add_action('admin_init', 'example_nag_ignore');
      function example_nag_ignore() {
      global $current_user;
      $user_id = $current_user-&gt;ID;
      /* If user clicks to ignore the notice, add that to their user meta */
      if ( isset($_GET['example_nag_ignore']) &amp;&amp; '0' == $_GET['example_nag_ignore'] ) {
      add_user_meta($user_id, 'example_ignore_notice', 'true', true);
      }
      }
      </pre></code>

      Source: http://wptheming.com/2011/08/admin-notices-in-wordpress/

  5. #7 says "adjust the path and name of the image"

    I'm not exactly a beginning coder, but I can't see where the path and image name are in that snippet.

    • Tom Ewer says:

      Apologies Joel – WordPress mangles the code snippets every time I enter the visual editor (one of my real WordPress pet hates). The code should be displaying correctly now.

  6. Jacques says:

    – snippet 8 falls partially outside the 'code box'
    – not sure: do you need the favicon code? I think placing it in your root and/or theme folder, it will be picked up (might depend on browser, though)

    In general, thanks for this list – the less plugins, the merrier. In ManageWP, 'run code' provides this functionality, right? Can we just add the above snippets and run them?

    • bungeshea says:

      No, ManageWP's 'run code' functionality only executes the code once. You need to use the Code Snippets plugin (as mentioned above) to have them run every time someone visits your site.

Speak your mind