Creating a WordPress Custom Functions Bible – and Snippets to Get You Started

Creating a WordPress Custom Functions Bible – and Snippets to Get You Started

To hazard a guess, I would estimate WordPress developers realize the benefits of storing and reusing code snippets after their third or fourth WordPress site.

It not only ensures your development practices stay consistent from project to project, but also greatly improves your development efficiency.

Time saved from being able to avoid trawling through industry blogs and scouring recent projects functions.php files searching for that gem of a function you knew you once used can dramatically improve a project’s turnaround time.

Suggesting developers should save every snippet of code inside a mammoth “custom-functions-bible.php” file is not only completely ridiculous but also counterintuitive for development efficiency. Something as simple as creating a functions.php boilerplate or taking advantage of Adobe Dreamweaver’s snippets should suffice.

Code repositories are not only great ways to improve individual efficiency, but team efficiency, too. By encouraging your team of developers to take advantage of online resources such as using GitHub to build useful code repositories that are shared and updated within your team will help increase efficiency and learning.

In order to get you started, I have compiled a selection of some of my favorite custom functions for you to begin using throughout your projects.

Functions bible
Create a repository of your custom functions for easy access.

Limiting Words

Like many developers I often find myself needing to limit the length of a dynamic piece of content. Achieving these results by limiting the characters using simple PHP functions like substr() may be easy to implement but look messy for front-end users as the final word will often be chopped in half.

Aiming to limit your content by an amount of words is a much more elegant approach to this issue. Limiting a post by an amount of words can be achieved with the use of the built in WordPress function the_excerpt(); As standard the_excerpt() limits your content to the first 55 words, after which a […] is appended onto the post.

Great as this is, I often need more control over the length of the posts retrieved within a loop. To do this we have two options:

Option One – Controlling Excerpt Length Using Filters

My first recommendation would be to change the default limit of the_excerpt() using filters. The method outlined below simply needs to be added to your themes functions file and globally your posts will be limited to your desired amount.

1
2
3
4
5
function custom_excerpt_length( $length ) {
return 20;
}

add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Option Two – Controlling Content Length Using A Custom Function

It is easy to run into issues with option one as it is a global solution to limiting the excerpt. Some developers may not be looking to limit the_excerpt() or may have numerous different custom loops which each require different excerpt lengths to be set. Unfortunately, option one isn’t going to solve these common issues.

By creating a custom function to look after this task allows developers more control over exactly what type of content to limit. The following function takes two parameters:

  1. $string – The string that needs be limited for example get_the_excerpt().
  2. $max_words – The maximum amount of words you would like to show.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Limit Your Website Excerpt */

function word_limit($string, $max_words){

$post_words = explode(' ', $string);

$count = count($post_words);

$post_words = implode(' ', array_slice($post_words, 0, $max_words));

if($count > $max_words):

return $post_words . '...';

else:

return $post_words;

endif;

}

A Very Brief Overview Of How The Function Works

The function begins by taking the string and exploding it into an array, once in an array we are able to limit the array using the PHP function array_slice() and implode it back onto our page. If the content has been limited the function appends a “…” to the end of the post.

This function is a perfect example of how to correctly limit a piece of content on your website.

Removing WordPress Version Number

Improving WordPress security should not be overlooked on the sites you develop. I often speak to developers who have the “That Wont Happen To Me” attitude that I also once had. Trust me, coming from someone who has experienced the shame of being hacked, there is nothing more embarrassing and sole destroying than your site featuring a black screen containing the words “You Have Been Hacked By …” in a 125px font.

Developers who have experienced this type of hack will know the subsequent phone call to their client is not an enjoyable one.

I urge all developers to even take simple measures to help ensure their website’s security. For example, you are able to dramatically decrease your chances of being hacked by simply removing the WordPress version number from your source code using the following action in your functions.php file:

1
remove_action('wp_head', 'wp_generator');

Although this is an extremely simple security measure and will not guarantee full security, it does help to hinder hackers.

I recommend to wise readers taking WordPress security seriously to read WordPress Security: The Ultimate Guide by Kevin Muldoon.

Display All Site Settings

When developing themes and plugins I often find myself darting over to phpMyAdmin to check and modify specific settings.

The below code removes the need to manually access phpMyAdmin for these types of mundane tasks, by simply adding an “All Settings” tab that enables users to view an extensive list of site settings found within your database related to your site.

The function also ensures that the tab is only viewable to admin users and is an excellent and time efficient way to edit global website settings.

1
2
3
4
5
6
7
// CUSTOM ADMIN MENU LINK FOR ALL SETTINGS

function all_settings_link() {
add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}

add_action('admin_menu', 'all_settings_link');

Restrict Authors to Edit Only Their Own Posts and Media

Developing and managing large industry related blogs can be one hell of a task made even more challenging by the range of different authors you employ.

Often large WordPress blogs can have multiple bloggers adding media, creating posts and using the dashboard at the exact same time, and boy can it get confusing quickly.

A great way to improve your authors’ experience is to streamline their access within the WordPress Media tab. The following snippet allows authors to only view the media they have uploaded themselves, which allows for a much smoother blogging experience:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* Only See Own Attachments */

add_action('pre_get_posts','users_attachments');

function users_attachments( $wp_query_obj ) {

global $current_user, $pagenow;

if( !is_a( $current_user, 'WP_User') )
return;

if( 'upload.php' != $pagenow )
return;

if( !current_user_can('delete_pages') )
$wp_query_obj->set('author', $current_user->id );
return;

}

Replace WP Admin

Delivering to clients a unique individual experience is crucial to customer satisfaction. This can easily be achieved by adding small personal touches throughout the site and the WordPress backend.

I have found something as small as switching the WordPress logo on the login screen to your customer’s branding really helps to deliver this experience to your clients.

The code below allows you to switch the login logo to a more preferable image by simply changing the attachment id:

1
2
3
4
5
6
7
8
9
10
11
12
add_action( 'login_head', 'login_logo' );

/**
* Replaces the login header logo
*/

function login_logo() {

$image_attributes = wp_get_attachment_image_src( 1, 'full' );
echo '<style> .login h1 a { background-image: url( ' . $image_attributes[0] . ' ) !important; }</style>';

}

I recommend taking this approach one step further by addressing two other small issues. The logo by default links through to the WordPress.org website and also has the HTML title “Powered by WordPress”. The following two functions ensure if clicked the user is taken to the site’s homepage and also modifies the title tag to contain the site title.

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
add_filter( 'login_headerurl', 'login_logo_headerurl' );

/**
* Replaces the login header logo URL
*
* @param $url
*/

function login_logo_headerurl( $url ) {
$url = home_url( '/' );
return $url;
}

add_filter( 'login_headertitle', 'login_logo_headertitle' );

/**
* Replaces the login header logo title
*
* @param $title
*/

function login_logo_headertitle( $title ) {
$title = get_bloginfo( 'name' );
return $title;
}

Removing Post Meta Boxes from Posts and Pages

When creating a WordPress page or post, users can often become overwhelmed by the amount of unnecessary fields found throughout the page, ranging from Custom Fields to Author Meta boxes.

Although they can be removed using the screen options drop down tab, I always make a habit of removing any fields that aren’t necessary to the website or user at the start of the project. After all why leave them there?

This extremely useful custom function makes use of the built in WordPress remove_meta_box() function. To remove a meta box that appears on both pages and posts we have to declare the function for each.

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
// REMOVE POST META BOXES

function remove_metaboxes() {

/* Posts */

remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Status Metabox
remove_meta_box( 'commentsdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'revisionsdiv','post','normal' ); // Revisions Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Trackback Metabox

/* Pages */

remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','page','normal' ); // Author Metabox

}

add_action('admin_menu', 'remove_metaboxes');

Conclusion

The custom functions featured in this post feature regularly within the functions.php files for my themes. My hope is that you also consider the use of them in your sites going forward.

There are absolutely hundreds of extremely useful functions that we simply don’t know exist as they have never been shared! Well this is the time to change that mentality.

I encourage all readers to share their own favorite snippets in the comments below, and just maybe, together, we can create our own “custom-functions-bible.php.”