Tools WordPress Themes

Essential Code Snippets for Your WordPress Theme’s functions.php

5/5 (1)

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 change the display of your WordPress install. But these codes are special because they can affect places even outside of your core theme files!

In this article I would like to share 20 helpful code snippets you can include in your functions.php file. All you need to do is create this file inside your theme directory and then copy over these codes inside the PHP <?php ?> brackets. Along with this collection you may also search on Google and find loads of similar resources for WordPress developers.

1. Custom Excerpt Length

1
2
3
4
5
6
7
8
9
10
/**
 * code #1 - update the post excerpt character length
 * @param integer
 * @return integer
 */
function my_excerpt_length($length) 
{
	return 65; 
}
add_filter('excerpt_length', 'my_excerpt_length');

This small block of code will allow you to customize the total number of characters allowed in your post snippets. These are the brief descriptions which are produced automatically by WordPress for each blog article. They appear as the page description, and also in queries like the search template.

Just update the number to whatever character limit you would like to impose. My example of 65 is a fair set for brief content - Google usually recommends anywhere from 80-110 words for SEO descriptions.

2. Custom 'Read more' Text

1
2
3
4
5
6
7
8
9
10
11
/**
 * code #2 - replace 'Read more' text with new string same URL
 * @param string
 * @return string
 */ 
function new_excerpt_more($text) 
{  
	return ' [...]'; 
 
}
add_filter('excerpt_more', 'new_excerpt_more');

This is another quick snippet you can use to replace the default more text. You will notice this on your blog homepage when you have posts which are longer than the character limit, this will display a permalink to the article. Just replace the string to whatever output you'd like.

3. Remove #more from URL

1
2
3
4
5
6
7
8
9
/**
 * code #3 - remove #more hash from post URL
 * @param string
 * @return string
 */
function remove_more_link_jump($post) {
  return '&lt;a href="'.get_permalink($post->ID).'" class="read-more"&gt;'.'Read More...'.'&lt;/a&gt;';
}
add_filter('excerpt_more', 'remove_more_link_jump');

Similar to our last bit, you may have noticed the 'Read more' link appends a hash symbol onto the end of your permalink. This is supposed to jump readers down to the paragraph where they ended right before clicking the link. Many webmasters find this annoying, and so here is a quick block of code for turning off that feature.

4. Disable Automatic Paragraphs

1
2
3
4
/**
 * code #4 - remove automatic <p> tags in Wordpress editor
 */
remove_filter('the_content', 'wpautop');

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.

5. Clear Out Excess Header Tags

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * code #5 - removes excess Wordpress header tags from default themes. 
 *         feel free to customize the options to suit your own needs.
 */
function clean_wp_header() {
  remove_action('wp_head', 'wp_generator');
  remove_action('wp_head', 'rel_canonical');
  remove_action('wp_head', 'rsd_link');
  remove_action('wp_head', 'feed_links',2);
  remove_action('wp_head', 'feed_links_extra',3);
  remove_action('wp_head', 'wlwmanifest_link');
  remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
  remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
}
add_action('init', 'clean_wp_header');

By default WordPress will output a lot of meta tags and extra header details. If you don't mind keeping them in your code it's not a terrible idea. They are often great for SEO and help to give more credibility to your website. But some web developers would rather have a clean slate and get code processed much quicker.

Each of these remove_action() functions will remove a different piece from the WP head area. If you want to test out which line disables which features you should briefly comment out one line and see what appears in your source code.

6. Style 1st Paragraphs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * code #6 - append 'first' class onto the 1st <p> element in each post
 * source  - http://byjakewithlove.com/
 * @param string
 * @return string
 */
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');

I have included this feature which I originally styled for my own blog but have been using it frequently in other WordPress themes. You should add this code into your functions.php and then create some CSS styles to match. Target the class .first or p.first if you need to specify an element.

7. RSS Post Thumbnails

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * code #7 - add post thumbnails into RSS feed
 * source  - http://www.wpfunction.me/
 * @param string
 * @return string
 */
function add_feed_post_thumbnail($content) {
	global $post;
 
	if(has_post_thumbnail($post->ID)) {
		$content = get_the_post_thumbnail($post->ID, 'thumbnail') . $content;
	}
	return $content;
}
add_filter('the_excerpt_rss', 'add_feed_post_thumbnail');
add_filter('the_content_feed', 'add_feed_post_thumbnail');

By default your featured image and post thumbnails will not show up inside your WP RSS feed. I would love to see the WordPress developers include this as a core feature during an upcoming release. But for now it's easy enough to copy this chunk of code and append the thumbnail image URL.

8. Custom User Social Fields

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * code #8 - add & remove custom Wordpress social contacts from user profile
 * source  - http://wordpress.stackexchange.com/a/4125/8922
 * @param array
 * @return array
 */
function cusom_social_contact_links($contacts) {
  // Adding
  $contacts['twitter']  = 'Twitter';
  $contacts['youtube']  = 'YouTube';
  $contacts['dribbble'] = 'Dribbble';
 
  // Removing
  unset($contacts['yim']);
  unset($contacts['aim']);
  unset($contacts['jabber']);
 
  return $contacts;
}
add_filter('user_contactmethods','cusom_social_contact_links', 10, 1);

Once you log into the WordPress admin panel and find your profile page you will notice some extra contact fields. Users may fill out their own details for profiles such as Skype or Twitter. Using this code you may customize your own fields to include other methods of communication, or even other social media profiles.

9. Custom Admin Settings Menu

1
2
3
4
5
6
7
8
/**
 * code #9 - display custom admin menu with all links
 * source  - http://wordpress.stackexchange.com/a/1614/8922
 */
function full_admin_settings_links() {
  add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}
add_action('admin_menu', 'full_admin_settings_links');

If you would like direct access to all of the administrator's settings then definitely try out this brief snippet of code. For power users who know exactly where they need to go it's a lot easier navigating the backend. But it's also easy enough to comment out or even delete to revert back.

10. Remove Image Width/Height Attributes

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * code #10 - remove width/height HTML attributes from images
 * source   - http://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/
 * @param string
 * @return string
 */
function remove_image_size_atts($html) {
    $html = preg_replace('/(width|height)=\"\d*\"\s/', "", $html);
    return $html;
}
add_filter('post_thumbnail_html', 'remove_image_size_atts', 10);
add_filter('image_send_to_editor', 'remove_image_size_atts', 10);

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 1x1 empty blocks.

But similarly there are responsive image techniques which sometimes require not specifying a width or height. It's possible to upload images and then add the HTML yourself, but for users who don't know how this is a great solution. You should be able to remove other attributes as well by listing them inside the regular expression.

11. Hide Update Message from Users

1
2
3
4
5
6
7
8
9
10
/**
 * code #11 - remove Wordpress update message for everyone except Admin users
 * source   - http://wordpress.stackexchange.com/a/1585/8922
 */
global $user_login;
get_currentuserinfo();
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;"));
}

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.

12. Remove Excess Header Tags from Posts/Pages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/** 
 * code #12 - remove header meta tags from blog posts and pages.
 *       feel free to customize the options to suit your needs.
 * source   - http://wordpress.stackexchange.com/a/1569/8922
 */
function remove_default_post_metatags() {
 remove_meta_box('postcustom','post','normal');
 remove_meta_box('postexcerpt','post','normal');
 remove_meta_box('commentstatusdiv','post','normal'); 
 remove_meta_box('trackbacksdiv','post','normal');
 remove_meta_box('slugdiv','post','normal'); 
 remove_meta_box('authordiv','post','normal');
}
add_action('admin_menu','remove_default_post_metatags');
 
function remove_default_page_metatags() {
 remove_meta_box('postcustom','page','normal'); 
 remove_meta_box('postexcerpt','page','normal');
 remove_meta_box('commentstatusdiv','page','normal');
 remove_meta_box('trackbacksdiv','page','normal');
 remove_meta_box('slugdiv','page','normal');
 remove_meta_box('authordiv','page','normal');
}
add_action('admin_menu','remove_default_page_metatags');

One of the code snippets I mentioned earlier is used to remove unwanted tags in the document header. This is similar except we're targeting meta tags which display on posts and pages. These tags are often just taking up space and do not provide much real valuable information to search crawlers. But just as before, feel free to comment out or remove lines of code for testing which meta tags should stay and which need to go.

13. Add Thumbnails into 'Manage Posts/Pages' Table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/** 
 * code #13 - add post thumbnails into "manage posts/pages" admin table
 * source   - http://wordpress.stackexchange.com/a/6021/8922
 */
if(!function_exists('add_thumb_column') && function_exists('add_theme_support')) {
  add_theme_support('post-thumbnails', array('post', 'page'));
 
  function add_thumb_column($cols) {
    $cols['thumbnail'] = __('Thumbnail');
    return $cols;
  }
 
  function add_thumb_value($column_name, $post_id) {
    $width = 35;
    $height = 35;
 
    if('thumbnail' == $column_name ) {
      $thumbnail_id = get_post_meta($post_id, '_thumbnail_id', true);
 
      $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');
       }
    }
  }
 
  add_filter('manage_posts_columns', 'add_thumb_column');
  add_action('manage_posts_custom_column', 'add_thumb_value', 10, 2);
 
  add_filter('manage_pages_columns', 'add_thumb_column');
  add_action('manage_pages_custom_column', 'add_thumb_value', 10, 2);
}

If your website is prominently using the featured images in posts then you may consider adding this large function to your file. The two filter/action sets will add another column into the 'manage posts' and 'manage pages' table within the admin panel. This column will display a smaller thumbnail shot of the featured image for each piece of content.

Be aware that loading your pages will probably take just a couple extra seconds. Pulling images into the page is always a bit more tedious, and tack on the database query results as well. But it's a really nice piece of functionality worth testing out, if you have the time.

14. Display D/B Query Times & Resources

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * code #14 - display Wordpress database query times and memory consumption in footer
 * source   - http://wordpress.stackexchange.com/a/1866/8922
 */
function footer_stats_display($visible = false) {
  $stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory',
    get_num_queries(),
    timer_stop( 0, 3 ),
    memory_get_peak_usage() / 1024 / 1024);
 
  echo $visible ? $stat : "&gt;!-- {$stat} -->" ;
}
add_action('wp_footer', 'footer_stats_display', 20);

If you are curious about how your server handles each page load this may be worth adding into your document. This small block will add an HTML comment right at the end of each page in the wp_footer() function. You will see the total number of database queries, how long they took to perform, and how much memory was used on the server.

15. Get Current Template Details in Header

1
2
3
4
5
6
7
8
9
/**
 * code #15 - output the current post/page template name in your header area
 * source   - http://wordpress.stackexchange.com/a/3848/8922
 */
function display_template_name() {
  global $template;
  print_r($template);
}
add_action('wp_head', 'display_template_name');

This small block of code is more useful when debugging than anything else. But there are often times when I'm building a template and I cannot figure out why one page is rendering different than all the others. This usually relates to a template type issue, especially with custom post types.

Just add this bit into your functions.php file for a couple of seconds, enough time to pull down your results. When you reload the page you'll notice the PHP print_r() method directly outputs the content into your HTML. Be sure to remove this after using, or just comment out the block to hide it with /* */ syntax.

16. Customize Admin Page Footer

1
2
3
4
5
6
7
8
/**
 * code #16 - customize the admin page footer text
 * source   - http://wordpress.stackexchange.com/a/6005/8922
 */
function custom_admin_footer() {
  echo 'add your custom footer text and html here';
} 
add_filter('admin_footer_text', 'custom_admin_footer');

This isn't a piece of the layout where many people think to look, but WordPress users love customizations. If you want to update some new links or text into your admin panel footer area, just copy over this block of code and edit the string value. Whatever is being output to the page will display in your admin footer text area.

17. Sharpen Resized JPEG Images

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * code #17 - sharpen JPG/JPEG images when auto-resized in Wordpress
 * source   - http://wordpress.stackexchange.com/a/35526/8922
 * @param string
 * @return resource
 */
function sharpen_resized_jpeg_images($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'));
      break;
    case IMAGETYPE_PNG:
      return $resized_file;
    case IMAGETYPE_GIF:
      return $resized_file;
  }
 
  return $resized_file;
}   
add_filter('image_make_intermediate_size', 'sharpen_resized_jpeg_images', 900);

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. If you go to the original stack comment you can see a few example comparison images. There is clearly a huge different in quality and it's a very impressive customization.

18. Remove 'comments' Column from Manage Pages

1
2
3
4
5
6
7
8
9
10
11
/**
 * code #18 - remove 'comments' column from pages admin table
 * source   - http://wordpress.stackexchange.com/a/9990/8922
 * @param array
 * @return array
 */
function remove_comments_column($defaults) {
    unset($defaults['comments']);
    return $defaults;
}
add_filter('manage_pages_columns', 'remove_comments_column');

When looking at the Pages table in the administrator panel you will notice there is a small column for the comments count. This is obviously helpful when going through posts, however pages are not formatted the same way and do not usually allow comments. Simply copy/paste this code snippet into your document and you'll notice a much cleaner table when editing page content.

19. Custom Codex Search in Admin Panel

1
2
3
4
5
6
7
8
9
10
/**
 * code #19 - display a custom Wordpress codex search in the admin dashboard
 * source   - http://wordpress.stackexchange.com/a/3805/8922
 */
function wp_codex_search_form() {
  echo '&lt;form target="_blank" method="get" action="http://wordpress.org/search/do-search.php" class="alignright" style="margin: 11px 5px 0;">
    &lt;input type="text" onblur="this.value=(this.value==\'\') ? \'Search the Codex\' : this.value;" onfocus="this.value=(this.value==\'Search the Codex\') ? \'\' : this.value;" maxlength="150" value="Search the Codex" name="search" class="text"> &lt;input type="submit" value="Go" class="button" />
  &lt;/form>';
}
add_filter('in_admin_header', 'wp_codex_search_form', 11);

This is one of my personal favorite snippets because it's so useful on any WordPress install. Instead of opening a new tab to search your question in Google it's so easy to get right into the WordPress online code docs. The search form will automatically open in a new window so you won't lose any unsaved work.

20. TinyURL Shortcode Tags

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/** 
 * code #20 - get TinyURL for any post or page via shortcode tag
 * source   - http://wordpress.stackexchange.com/a/5741/8922
 * ex: [tinyurl] will output the TinyURL for the current page
 *     [tinyurl url="http://google.com/" title="google"] will output the TinyURL for Google.com
 */
function custom_tinyurl_shortcode($atts){
  extract(shortcode_atts(array(
   'url' => get_permalink(),
   'title' => ''
  ), $atts));
 
  if(!$title) $title = $url;
 
  if(false === ($cache = get_transient('tinyurl_'+md5($url)))):
    $cache = wp_remote_retrieve_body(wp_remote_get('http://tinyurl.com/api-create.php?url='.$url));
    // cached for 24 hours
    set_transient('tinyurl_'+md5($url), $cache, 60*60*24); 
  endif;
 
  return '&lt;a href="'.esc_url($cache).'">'.esc_attr($title).'&lt;/a>';
}
add_shortcode('tinyurl', 'custom_tinyurl_shortcode');

Many WordPress developers are creating shortcodes to embed into content. This makes it easier for writers to create full HTML widgets like video players and image slideshows. This snippet will create a shortcode which you may call in two ways. The first is simply [tinyurl] which will output the TinyURL version of the current page.

However you can pull a remote URL as a TinyURL by adding some optional parameters. The title="" parameter will display link text inside the <a href=""></a> tag. Otherwise your output text will be the same as the new TinyURL. Check out my comments in the source code for some more detailed examples.

Final Thoughts

I hope at least a few of these snippets may be useful for advancing web projects. The open source movement has really changed how we work and build digital products. I happen to be a huge fan of WordPress and I feel the CMS platform is only improving with age.

Definitely test out some of the codes above and see how they work on your own website. The functions.php WordPress theme file is powerful and you can perform some truly incredible updates with just a few lines of code. I would recommend keeping a backup, though, because one mistake will cause the whole theme to produce an error message. But along with my tips feel free to share your own thoughts with us in the discussion area below.

Here you can down the file with source code.