20 WordPress Code Snippets for Constructive Web Developers

Over the years WordPress has grown into the most popular CMS via the Internet. Its open source status coupled with a deeply committed development team has proven to advance quickly. And with even more web developers starting out today the community has risen dramatically.

Below I’ve collected a set of 20 awesome WordPress code snippets for all users to enjoy. Web developers will especially enjoy the collection as customizing WordPress has never been easier! I recommend applying only the bits of code you would need, and also ensure you add one at a time to avoid any rushed mistakes.

Increase Memory Limit

The memory limit for your server can become a problem once your blog gains traffic. To increase the amount of memory limit allowed in PHP use this simple line of code in your wp-config file.

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

Filter Loop Posts

One of the simplest ways to create custom featured articles is with WordPress loops. Custom loops will make the process simple as pie. The code below, for example, will pull articles only from the featured category. You can update this to include whatever you’d use.

query_posts('showposts=5&category_name=featured');
if ( have_posts() ) : while ( have_posts() ) : the_post();
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php the_content(); ?></p>
endwhile; else:
endif;
wp_reset_query();

Browser Caching with .htaccess

Is your site bogged down from so much repeat traffic? Slow page loads are the devil’s tool for loss of community. This short snippet can be added into your .htacess file

## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
## EXPIRES CACHING ##

Properly Include jQuery

jQuery is the best extensible JavaScript library to date. WordPress allows a simple way of including the latest version through an internal function.

<?php wp_enqueue_script("jquery"); ?>

Implement Maintenence Mode

Whenever you’re working on your blog and wish to blockade traffic from the main website, maintenence mode is your best option. Add the below function and action into your function.php file within your template folder.

function maintenace_mode() {
if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
die('Maintenance.');
}
}
add_action('get_header', 'maintenace_mode');

.htaccess Simple Login URL

Wish to clean up your WordPress login URL? This short code snippet added into your .htacess will allow you to access the login page from http://yoursite.com/login. This makes working with many authors a whole lot easier.

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

Custom Autosave Time Limit

WordPress’ Auto Save functionality will help you out more than once. However with this short line of code you can update how soon WP should save your draft. This can be added into your wp-config or functions.php within your theme folder.

# Autosave interval set to 5 Minutes #
define('AUTOSAVE_INTERVAL', 300);

Custom Admin Panel Logo

We have all seen the classic WordPress symbolism within the admin panel. Well with this bit of functionality inside your functions.php file it’s easy to build custom branding! Just be sure to upload admin_logo.png into your templates’ images folder.

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

Custom Admin Footer Text

At the same time you may wish to edit the footer text inside your admin panel. For those who run large blogs and magazines online branding is very important. This bit of code can be added into your functions.php along with the admin panel edits above.

function remove_footer_admin () {
echo 'Skyje is Awesome. Thank you <a href="http://wordpress.org">WordPress</a> for giving me this filter.';
}
add_filter('admin_footer_text', 'remove_footer_admin');

Dynamic Favicon

It’s simple to add your own link within the header.php file to create a favicon. However if you’d like to be a little more dynamic we can write a simple function inside our functions.php which adds our favicon into every page without fail. Below is the few lines of code required.

function blog_favicon() {
echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
}
add_action('wp_head', 'blog_favicon');

Remove Admin Sub-Menus

Sub menus inside the administrator panel can get annoying. This is especially true for blogs running many authors who aren’t familiar with the system. Add this small function into your functions.php file to replace and update your administration backend.

function remove_submenus() {
global $submenu;
unset($submenu['index.php'][10]); // Removes 'Updates'.
unset($submenu['themes.php'][5]); // Removes 'Themes'.
unset($submenu['options-general.php'][15]); // Removes 'Writing'.
unset($submenu['options-general.php'][25]); // Removes 'Discussion'.
}
add_action('admin_menu', 'remove_submenus');

Remove Update Notice

Getting annoyed seeing new update messages inside your admin panel? Well now we can remove it! Just use the code below and you’ll never be bothered with an update message anytime soon.

add_action('admin_menu','wp_hide_update');
function wp_hide_update() {
remove_action( 'admin_notices', 'update_nag', 3 );
}

Update for Relative Dates

If you’d like to have posts display a relative date instead of exact date/time, this short snippet is for you. As an example you can update posts and comments to read “3 weeks ago” or “6 months ago” instead of “July 12 2011”. Use the simple template below.

// For posts or pages
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';
// Commments
<?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; ?>

Implement Search Box in Nav Menu

It can be difficult editing your template to find room for a search box. WordPress isn’t always the most stable system when it comes to search queries – but with this code below things become much more manageable. Add this function into your functions.php file inside your template folder.

add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {
ob_start();
get_search_form();
$searchform = ob_get_contents();
ob_end_clean();
$items .= '<li>' . $searchform . '</li>';
return $items;
}

Disable All Default Widgets

WordPress out-of-the-box does come with a large amount of plugins and widgets. Granted these can be turned off within your theme files, this short function will give you a blank slate to work with. Add the entire function code inside your functions.php file.

function unregister_default_wp_widgets() {
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Search');
unregister_widget('WP_Widget_Recent_Comments');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);

Shortcodes for Widgets

If you are familiar with short codes you can also use this brief line of code to add one for each widget. This makes implementing widgets into your template literally a matter of a single code bit. Check out the brief example I’ve added below.

add_filter('widget_text', 'do_shortcode')

Google Analytics without Theme Edits

I’m sure as webmasters we are all familiar with using Google Analytics. It’s a short amount of JavaScript to implement and start tracking visitor information. This function inside your theme’s functions.php will automatically place your code on every single page dynamically. You just need to add your JS code inside the function by replacing the filler comment text.

<?php add_action('wp_footer', 'ga_custom');
function ga_custom() { ?>
// add google analytics code here!
<?php } ?>

Set HTML Default Text Editor

The WYSIWYG editor which comes default on install of WordPress can be annoying for those who enjoy working in HTML. I find that HTML is easily the best way to edit articles. With this short bit of code inside your functions.php it’s a simple matter to shift between default states.

// Set HTML as Default
add_filter( 'wp_default_editor', create_function('', 'return "html";') );

Set Minimum Post Word Count

If you have authors writing for your blog who aren’t often adding many details this snippet can save you a lot of management time. Simply update the count of words within this function to restrict articles from being published without more than X amount of words. This function should be placed inside your theme’s functions.php file.

function minWord($content) {
global $post;
$num = 100; //set this to the minimum number of words
$content = $post->post_content;

if (str_word_count($content) < $num)
wp_die( __('Error: your post is below the minimum word count.') ); }
add_action('publish_post', 'minWord');

Split Post Comments and Trackbacks

One bit of funcitonality which hasn’t been seen in WordPress at all is the ability to split between post comments and trackbacks. The two are entirely different and can be very confusing seeing them put together. This short bit of code should be added into your comments.php file inside your themes folder.

<ul class="commentlist">
<?php // only comments

<span style="white-space: pre;"> </span> <?php foreach ($comments as $comment) : ?>
<span style="white-space: pre;"> </span> <?php $comment_type = get_comment_type(); ?>
<span style="white-space: pre;"> </span> <?php if($comment_type == 'comment') { ?>
<span style="white-space: pre;"> </span> <li>//Comment code goes here </li>
<span style="white-space: pre;"> </span> <?php }
endforeach;
</ul>
<ul>
<?php // only trackbacks

<span style="white-space: pre;"> </span>foreach ($comments as $comment) : ?>
<span style="white-space: pre;"> </span> <?php $comment_type = get_comment_type(); ?>
<span style="white-space: pre;"> </span> <?php if($comment_type != 'comment') { ?>
<span style="white-space: pre;"> </span> <li> <?php comment_author_link() ?></li>
<span style="white-space: pre;"> </span> <?php }
endforeach;
</ul>

Conclusion

These are a few of the many great snippets created for WordPress CMS. Without the Internet and the power of open source it would be almost impossible for web developers to communicate so elegantly. It’s truly a special time we live where resources are shared so openly amongst a powerful community.

If you know of similar code snippets please feel free to share them in the comments section below. I am always looking for great new bits of code to test out and WordPress has a huge community of users.

Jake Rocheleau

Jake is a social marketing expert and Internet entrepreneur. He has built a few startup ideas and continues to write for many online design magazines. Check him out through google or follow his updates on Twitter @jakerocheleau.

You may also like...

8 Responses

  1. aShocka says:

    Awesome list, thank you!
    I only have a problem with the dynamic favicon – I can’t seem to get it work. Where should I put the icon for it to work properly?

  2. Piet says:

    Nice list, most of them I knew already. But the one to “Implement Search Box in Nav Menu” was completely new to me and very helpful! Thanks!

  3. rax says:

    All the tips are great !

    I was just wondering, whether it is easy to implement Ajax in our wordpress blog or not ?
    If it is so,then how to implement it ?
    Any one can help me out ?

    thanks
    Rax

  4. I was looking for an easy Site Maintenence Mode solution without the use of any plugin. Your solution works like a charm!

    Thanks for sharing this

  5. Thank for this tricks,,,

  6. Susan says:

    A quick question, when i implement “Implement Maintenence Mode” script in my wordpress. Will this return the status code 200 or 302 when user or search engine requests the website.

  7. TC says:

    Thank you! These are super to use on my blog! Have had that problem with memory already.
    Is it possible this error shuts down the whole server? I would think a VPS server would be capable off handling a WP blog.

  8. Ryan S says:

    thanks for the great collections, this is very useful in my web development ;)

Leave a Reply