HTML5 Zone is brought to you in partnership with:

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5. Paul is a DZone MVB and is not an employee of DZone and has posted 128 posts at DZone. You can read more from them at their website. View Full User Profile

Useful WordPress Utility Functions

02.19.2013
| 1789 views |
  • submit to reddit

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 );

Make A Link Clickable

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 );

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 plugin_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__ ) );

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



Published at DZone with permission of Paul Underwood, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)