Useful WordPress Utility Functions

In this article we are going to look at some of the utility functions that you can take advantage of if your website is built using Wordpress. If you have a look at some of these functions you will understand how you can use Wordpress not just for a simple blog, not just for a CMS but for an application framework. These utility functions can be used in any of the plugins or themes you create within Wordpress. Some of these functions you may not of heard of, some of them you might of seen in other Wordpress tutorials. Hopefully you will see that next time you need to do a common piece of code in your development, first check if it already exists in Wordpress. Most of these functions can be found in * /wp-includes/functions.php, /wp-includes/formatting.php, /wp-includes/general-template.php*.

Form Helper Functions

There are 3 main form functions which are very useful when you are creating a new form in the admin area of Wordpress. When you return data from the database and need to pre-populate the form with this data then these functions can be really useful. These function are:

  • checked() - Compares two values and they match it will return a checked attribute inside a HTML element.
  • selected() - Compares two values and they it will return a selected attribute inside a HTML element.
  • disabled() - Compares two values and they it will return a disabled attribute inside a HTML element.

These all take the same three parameters, the first is the value, the second is the current value and the third is a boolean to echo the result.

checked( $checked, $current = true, $echo = true );
selected( $selected, $current = true, $echo = true );
disabled( $disabled, $current = true, $echo = true );


<input type="checkbox" value="1" name="checkbox" <?php checked( $value, '1', true); ?> />


<select name="select">
     <option value="1" <?php selected( $value, '1', true);?>>1</option>
     <option value="2" <?php selected( $value, '2', true);?>>2</option>
     <option value="3" <?php selected( $value, '3', true);?>>3</option>
     <option value="4" <?php selected( $value, '4', true);?>>4</option>
     <option value="5" <?php selected( $value, '5', true);?>>5</option>
</select>


<input type="text" name="disabled_textbox" <?php disabled( $value, 'disabled', true); ?> />

Join File Paths

If you need to join a couple of path files together then there is a useful function called path_join(), which you can provide 2 paths and will return a string of the two paths together.


$join_string = path_join( $base, $path );

Check If Path is Absolute

If you need to find out if a path is absolute then Wordpress has a function path_is_absolute() which will return a boolean value on if this is an absolute path.


$absolute_path = path_is_absolute( $path );

Create Recursive Directories

If you need to create a recursive folder directory from a file path, you can use the Wordpress function wp_mkdir_p(). This means that if you have a file path of /here/are/some/new/folders and pass this into the wp_mkdir_p( $path ) function you will get a new folder directories created for each one of these folders.


wp_mkdir_p( $path );

Get A Unique Filename

When you are adding a file to a directory, you would normally check to see if this filename is unique so you won't have to overwrite the existing file. There is a Wordpress function wp_unique_filename() which you will give a directory and a filename, the code will check to see if this filename exists inside the directory, if a file already exists then it will return the filename with a number appended to the end.


$unique_filename = wp_unique_filename( $directory, $filename );

Ensure Trailing Slashes

To make sure that there is always a trailing slash on the end of a file path then you can use the function * *trailingslashit()**, this will take a filepath and will make sure that it only has one trailing slash on the end.


$trailingslashFilename = trailingslashit( $filepath );

Remove Trailing Slashes

There is also an opposite of the above there is a function called untrailingslashit() which will take a filename and will remove all trailing slashes from the filepath.


$noTrailingSlashes = untrailingslashit( $filepath );

Display File Sizes

If you have a video or image website where people need to download something, most of the time the website will give them an indication on the size of the file. With the Wordpress function size_format(), you can pass in the number of bytes the file is and it will return the best way to display this data. For example if you pass in 1024 bytes then it will return 1kb. If you pass in the number 1048576 bytes and the function will return 1MB.


size_format( $bytes, $decimals );

Get Type Of File From Extension

There is a Wordpress function called wp_ext2type() which if you can provide it with a file extension and it will return what type of file it is. For example if you pass in the the extension png it will return that this is an image. This is really useful function to use if a user uploads a file you can get the extension and work out what type of file they uploaded.


wp_ext2type( $ext );

Get Human Readable Time Difference

In Wordpress you can display the date of the post, but some website that post a couple of times a day might want to display the dates like Twitter does. This is human readable time difference, 2 days ago, 10 minutes ago, 4 hours ago. In Wordpress there is a function called human_time_diff() which you can pass in a timestamp and it will work out how many days, hours, minutes ago this date was.


human_time_diff( $from, $to = NULL );

Check If Using A Mobile

Check if the visitor is viewing your site on a mobile device by using the Wordpress function wp_is_mobile().


<?php if ( wp_is_mobile() ) {
	/* Display and echo mobile specific stuff here */
} ?>

Set Header Status Code

To set the status code of the HTTP header, instead of using the PHP header function, Wordpres has it's own function to make this easier. You can use the function status_header() to change the status code.


status_header( $code );

For example to set the status code on a 404 page just use the following function.


status_header( '404' );

Encode Email Address

Stop spam bots from scanning your website for your email address by converting the email address into HTML entities. Use the Wordpress function antispambot(), pass in the email address and it will return the HTML entities convert version of the email address. You can display the return of the this function safely on your website without spam bots getting your email address.


$converted_email = antispambot( $email );

If you have a URL or an email address and what to add a link around this text so people can click to go to this webpage or send a email to someone. Wordpress comes with a built in function to make a valid URL or email address clickable by adding the correct link around some text.


$string = "This is a long text that contains some links like http://www.wordpress.org and http://www.wordpress.com .";
echo make_clickable($string); 

Check Email Addresses

Want to check is a string provide is a valid email address, use the function is_email() passes in the email address you want to check, if this return true then it is a valid email address.


if(is_email( $email ) )
{
    // $email is a valid email address
}

Trim A String

If you want to get a except of a string you can use the wp_trim_excerpt() function that will reduce the string provided to a maximum of 55 words if it is more then a [...] will be added to the end of the string.

$excerpt = wp_trim_excerpt( $text );

If you want to change this to a different number of words then use the function wp_trim_words() you can give this function text and the number of words you want to return.

$oneHundredWords = wp_trim_words( $text, 100 );

Sanitize Title

This function is what Wordpress will use to generate the URL slugs from your post titles. This function to take your title and sanitize it by removing all whitespace and replacing them with dashes.

<?php
echo sanitize_title_with_dashes("I'm in LOVE with WordPress!!!1");
// this will print: im-in-love-with-wordpress1
?>

SSL

If you want to check if SSL is being used then Wordpress has a function called is_ssl() which will return a boolean on if SSL is currently being used.

if(!is_ssl())
{
    // this page requires SSL to be active
    return;
}

Plugin URL

An important function I have found myself using a lot is the plugins_url() function, you give this function the filepath and it will return with the URL to this plugin. It is very useful to use when you need to include javascript or stylesheets with your plugin.

$url = plugins_url( $path, $plugin );

If you want to include a stylesheet from within a plugin the best way to use this is to use the global variable * FILE* as the second parameter, this will always return the URL root of the plugin. So if your stylesheet is in a css folder on the root of your plugin you will enqueue it by using the following code.

wp_enqueue_style('stylsheet', plugins_url( 'css/style.css', __FILE__ ) );

Pluck Fields From Object

Using the function wp_list_pluck you are able to pass the function an array of objects or arrays and get out any property that you need.


<?php wp_list_pluck( $list, $field, $index_key = null ); ?>


<?php
$foods = array(
	array(
		'name'  => 'Banana',
		'color' => 'Yellow',
	),
	array(
		'name'  => 'Apple',
		'color' => 'Red',
	),
	array(
		'name'  => 'Lettuce',
		'color' => 'Green',
	),
	array(
		'name'  => 'Apple',
		'color' => 'Red',
	),
);

$food_colors = wp_list_pluck( $foods, 'color' );
?>

There are many other useful functions that you can find hidden away in the Wordpress code, which ones do you use?

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring