.. Your Daily Design Dosis

10 useful WordPress code snippets for your functions.php

| Comments Off on 10 useful WordPress code snippets for your functions.php

Any web developer who is familiar with WordPress knows about the functions.php file in your theme directory. This can include PHP code such as filters or functions to extend or enhance WordPress without utilizing a plugin.

More often than not I have found that by analyzing the code of plugins I was able to strip out the piece of code I wanted and hard code it into my functions.php. This provided me with the exact functionality I needed without unnecessary elements, causing longer loadtime, including non-validated codes, not working scripts, etc..

The point is any plugin can crash your WordPress website functionality in some cases, or even worse, an (not updated) plugin could be a possible backdoor for hackers to start an attack, and infect your database with some kind of script or virus.

But before I begin, as always, a word of warning ..

Note: These hacks worked at the time they were published, but as new versions of WordPress are released, some may no longer work. Please backup your theme before attempting any hacks so you can restore things if something goes wrong.

There are a lot more WordPress hacks and/or code snippets here in the gonzoblog, take a look in our tag-list WordPress Hacks.

Hide or Remove Categories from a WordPress Homepage

When displaying your latest posts on the homepage, you might want to exclude some categories from displaying on this page. There are many reasons why you would want to do this. You might want to keep your homepage for only news posts and relegate the rest of the posts to other sections accessed through the menu.

In your theme’s functions.php file, just insert the following code, replacing the category IDs with the ones you want to exclude:

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-5, -34'); // change category IDs
    return $query;

add_filter( 'pre_get_posts', 'exclude_category_home' );


Prevent WordPress to display login errors

By default, when you (or someone else) fail to login on your wp-admin, WordPress displays an error message. While those messages might be useful, they can also be used by hackers to track their progress.

Here is a nice tip to prevent WordPress from displaying login errors. Paste the following line of code into your functions.php file:

add_filter('login_errors', create_function('$a', "return null;"));

Once you saved the file, WordPress will not display any login error messages anymore.


Redirect your author archive link to your “About” page

By default, when someone click on your author posts URL, he is redirected to your author archive page. It is useful on multi-author blogs, but if there’s only one author on your blog, author archives are pointless. Here is a quick tip to redirect your author archive link to your “About” page.

This code have to be pasted into your functions.php file. Don’t forget to replace about on line 4 by the slug used by your “About” page.

add_filter( 'author_link', 'my_author_link' );

function my_author_link() {
	return home_url( 'about' );


Disable Automatic Paragraphs

This is another heavy customization for mid-to-advanced level WordPress users. When editing a post or page you may notice WordPress automatically embeds content with <p> tags. Whenever you hit the Return key WordPress will format each block of text. This is a simple filter which disables the feature entirely.

/* remove automatic <p> tags in WordPress editor */ 
remove_filter('the_content', 'wpautop');

Source Unknown

WordPress shortcode to easily integrate a Google Map on your blog

Google Maps are very useful to show locations on your blog, but they can be a bit tricky to integrate, especially for client or non tech-savvy users. Here is a shortcode that will make Google Maps integration super easy. To create the shortcode, paste the code below into your functions.php file:

function rockable_googlemap($atts, $content = null) {
               "width" => '940',
               "height" => '300',
               "src" => ''
   ), $atts));

return '<div>
         <iframe src="'.$src.'&output=embed" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="'.$width.'" height="'.$height.'"></iframe>

add_shortcode("googlemap", "rockable_googlemap");

Once you saved your functions.php, you can start integrating Google Maps into your posts and pages. To do so, get the url of the map you’d like to display, and use the shortcode as shown below:

[googlemap src="google_map_url"]

or with custom width and height parameters:

[googlemap width="600" height="250" src="google_map_url"]



Remove Image Width/Height Attributes for RWD

When you upload an image into WordPress the code will automatically include a width and height attribute onto the HTML tag. This data is often helpful when your page is still loading images, users will see a box placeholder instead of tiny 1×1 empty blocks.

But similarly there are responsive image techniques which sometimes require not specifying a width or height. It’s now possible to upload images (also after adding a caption) from within the post itself.

//remove inline width and height added to images
add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );

// Removes attached image sizes as well
add_filter( 'the_content', 'remove_thumbnail_dimensions', 10 );
function remove_thumbnail_dimensions( $html ) {
    	$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    	return $html;


How to Remove Settings Menus From the WordPress Dashboard

Have you ever wanted to remove a menu page from the WordPress dashboard? Perhaps you’re building a site for a client who gets confused by the settings menu.

/* Remove Settings and Posts Menu */

	add_action( 'admin_menu', 'my_remove_menu_pages' );

	function my_remove_menu_pages() {


Hide Update Message from Users

This code will only display the WordPress update message to Administrators of the website. It is almost pointless for authors or editors to see this information because they do not usually have the ability to update the website. Only administrators would have this ability, and so this code snippet will keep your backend running a little more smoothly.

/*remove WordPress update message for everyone except Admin users */
global $user_login; 
if(!current_user_can('update_plugins')) { 
   add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');" ), 2); 
   add_filter('pre_option_update_core', create_function('$a', "return null;")); 


Sharpen Resized Images (only jpg)

Please note upfront that this code will only work for JPG/JPEG image types. However that being said, this is definitely worth using in your code if you ever upload jpegs. Check the Source Link if you want to see some comparison images. There is clearly a huge different in quality and it’s a very impressive customization.

function ajx_sharpen_resized_files( $resized_file ) {

    $image = wp_load_image( $resized_file );
    if ( !is_resource( $image ) )
        return new WP_Error( 'error_loading_image', $image, $file );

    $size = @getimagesize( $resized_file );
    if ( !$size )
        return new WP_Error('invalid_image', __('Could not read image size'), $file);
    list($orig_w, $orig_h, $orig_type) = $size;

    switch ( $orig_type ) {
        case IMAGETYPE_JPEG:
            $matrix = array(
                array(-1, -1, -1),
                array(-1, 16, -1),
                array(-1, -1, -1),

            $divisor = array_sum(array_map('array_sum', $matrix));
            $offset = 0; 
            imageconvolution($image, $matrix, $divisor, $offset);
            imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
        case IMAGETYPE_PNG:
            return $resized_file;
        case IMAGETYPE_GIF:
            return $resized_file;

    return $resized_file;

add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);


Restrict wp-admin access to certain users

Adding this snippet to the functions.php of your wordpress theme will restrict wp-admin access to certain users as defined at http://codex.wordpress.org/Roles_and_Capabilities. And also still allows for user access to admin-ajax.php, async-upload.php.

function restrict_access_admin_panel(){
                global $current_user;

	if (
			// Look for the presence of /wp-admin/ in the url
			stripos($_SERVER['REQUEST_URI'],'/wp-admin/') !== false
			// Allow calls to async-upload.php
			stripos($_SERVER['REQUEST_URI'],'async-upload.php') == false
			// Allow calls to admin-ajax.php
			stripos($_SERVER['REQUEST_URI'],'admin-ajax.php') == false
		) {

				// Does the current user fail the required capability level?
                if (!current_user_can('activate_plugins')) {
                        wp_redirect( get_bloginfo('url') );
        add_action('admin_init', 'restrict_access_admin_panel', 1);


Bonus Hack (NOT for functions.php!): SQL query

Get rid of unused post revisions

WordPress have a feature which saves various copies of your posts in order to allow you to compare revisions or restore an older version of your posts. This is very useful, but it also take a lot of space in your database. Here is a very handy SQL query that will instantly delete all posts revisions as well as meta associated with it.

Just run the following query on your WordPress database, and all revisions (As well as meta associated with it) will be deleted from your database.

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



Author: Jan Rajtoral

Jan Rajtoral AKA Gonzo the Great is the Founder of and Designer at gonzodesign, providing design services across the full spectrum of Brand Identity, Graphic Design, Print and Advertising Design & Website Design.

Sorry, comments for this entry are closed at this time.