20+ Useful But Often Overlooked Utility Functions In WordPress

Today I bring you 20+ handy built-in WordPress functions. Some of them you may already know and use every day, while others you’ve probably never heard of as they’re usually not mentioned in WP tutorials or even the WordPress Codex. Being aware of these functions and knowing how to use them will save you time and make a number of common WordPress development tasks easier.

Personally, I wish I had learned about some of the things listed below earlier. It would have saved me from reinventing the wheel a couple of times 🙂

Return Functions

When dealing with WordPress hooks and callbacks, sometimes you will need a function that simply returns a predefined value like true or null. Luckily, WP has a whole bunch of built-in functions designed just for that purpose:

function __return_true();
function __return_false();
function __return_null();
function __return_empty_array();
function __return_zero();

For example, to enable the ‘menu_order‘ filter that lets you change the sort order of admin menus, you need to ensure that the ‘custom_menu_order’ filter returns true. Instead of writing your own callback, use __return_true:

add_filter('custom_menu_order', '__return_true');

Another common use case is disabling the admin bar:

add_filter('show_admin_bar', '__return_false');

Form Helpers

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

These functions compare the first two arguments and output the appropriate HTML attribute (e.g. checked=”checked”) if they match. Set $echo to false to make them return the attribute instead.

Example:

//Output a drop-down list of options and select the current setting.
$colours = array('red', 'green', 'blue');
$currentColour = get_option('my_colour_option');

echo '<select name="my_colour_option">';
foreach($colours as $colour) {
	printf(
		'<option value="%s"%s>%s</option>',
		esc_attr($colour),
		selected($currentColour, $colour, false),
		$colour
	);
echo '</select>';

URL Helper Functions

build_query

function build_query( $arguments );

Build a URL query string based on an array of query arguments. Works like the native PHP function http_build_query(), but is backwards-compatible with older PHP versions.

add_query_arg

//Can be called either with an argument name and value,
//or an array of query arguments.
function add_query_arg($name, $value, $uri = false);
function add_query_arg($queryArgs, $uri = false);

This function will add one or more query arguments to a URL. If you omit the URL, it will use the current URL. This means you can also use it to retrieve the URL of the current page:

$currentUrl = add_query_arg('__dummy_arg', false);

add_query_arg will strip any arguments set to false from the query string, so the above code will return just the current URL.

remove_query_arg

function remove_query_arg( $key, $uri = false );

The opposite of add_query_arg. Removes one or more query arguments from a URL. $key can be either an argument name, or an array of names. Again, if you omit the URL, it will remove the specified argument(s) from the current URL.

is_ssl

function is_ssl();

Check if the current page was loaded over SSL / HTTPS. Returns true if SSL is in use, or false otherwise.

Array Manipulation

wp_parse_args

function wp_parse_args( $args, $defaults = '' );

Merges user arguments together with a defaults array. This function will return an array containing all values from $args + any values from $defaults that don’t have a matching key in $args.

$args can be any of the following:

  • An associative array.
  • An object.
  • A query string (or any “&”-separated list of name=value pairs).

wp_parse_args() can be useful for e.g. parsing plugin settings:

$settings = get_option('my_settings', array());
$settings = wp_parse_args($settings, array(
    'colour'          => 'blue',
    'frob_widget'     => true,
    'another_setting' => 123,
));

See also: array_merge().

wp_array_slice_assoc

function wp_array_slice_assoc( $array, $keys );

Retrieve all items with the specified $keys from the input $array. Example:

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => '...');
$keys = array('a', 'c', 'x');
$slice = wp_array_slice_assoc($array, $keys);
print_r($slice); //Array ( [a] => 1 [c] => 3 )

wp_list_pluck

function wp_list_pluck( $list, $field );

Extracts the value of the specified $field from each item in $list and returns all extracted values as an array. For example, this code will output the titles of the 5 most recent posts:

$recentPosts = get_posts();
$titles = wp_list_pluck($recentPosts, 'post_title');
print_r($titles);

wp_list_filter

function wp_list_filter( $list, $arguments = array(), $operator = 'AND' );

This utility function is a fairly advanced one. It filters a $list of objects based on a set of key=value $arguments and returns only the objects that match (or don’t match, if $operator = ‘NOT’) the arguments.

Here’s a somewhat contrived example that retrieves a list of the recent posts that have at least one comment:

$recentPosts = get_posts();
$postsWithComments = wp_list_filter(
	$recentPosts,
	array('comment_count' => 0),
	'NOT'
);

wp_filter_object_list

function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false );

This function is almost identical to wp_list_filter (see above), except that you can tell it to return only a specific $field from each $list item instead of the entire object. See also: wp_list_pluck.

File System Utilities

path_join

function path_join( $base, $path );

Joins two filesystem paths together. Plain and simple:

$path = path_join('/my/awesome/path/to/', '/some/file.txt');
echo $path; //Outputs "/my/awesome/path/to/some/file.txt"

If the $path argument is already an absolute path, path_join will just return it without modification.

Notice: Despite what the source code comments in functions.php may imply, this function does not resolve relative paths for you. It just concatenates two strings together. Example:

$path = path_join('/foo/bar/', '../baz.txt');
echo $path; //Outputs "/foo/bar/../baz.txt", not "/foo/baz.txt".

path_is_absolute

function path_is_absolute( $path );

Checks if $path is an absolute file-system path. A couple of examples:

$absolute = path_is_absolute('/an/example/path');
var_dump($absolute); //true
$absolute = path_is_absolute('../an/example/path');
var_dump($absolute); //false

wp_mkdir_p

function wp_mkdir_p( $target );

Recursively create a directory path. wp_mkdir_p will create directories as necessary to ensure that the $target path exists and is a directory. Example:

wp_mkdir_p(WP_CONTENT_DIR . 'make/it/so');

And here’s what the WP directory structure might look like before and after running the example code:

get_temp_dir

function get_temp_dir();

Determines a writeable directory suitable for temporary files. Specifically, get_temp_dir will try all the following paths (in order) and return the first writeable directory it finds:

  1. The directory specified by the WP_TEMP_DIR constant (if set).
  2. /wp-content/
  3. The directory returned by sys_get_temp_dir().
  4. The temporary directory PHP uses for storing uploaded files. It’s controlled by the upload_tmp_dir setting in php.ini.
  5. /tmp/

Note: This list is based on WP 3.5 (alpha) and may not be completely accurate for other versions of WordPress.

wp_unique_filename

function wp_unique_filename( $directory, $filename, $unique_filename_callback = null );

Get a filename that is sanitized and unique for the given $directory. If the input $filename is not unique, this function will add a number before the file extension, and keep incrementing the number until it comes up with a filename that’s not already in use.

Example:

//Assume "photo.jpg" and "photo1.jpg" already exist in /wp-content/.
$filename = wp_unique_filename(WP_CONTENT_DIR, 'photo.jpg');
echo $filename; //Outputs "photo2.jpg"

trailingslashit & untrailingslashit

function trailingslashit($string);
function untrailingslashit($string)

trailingslashit will modify the input $string so that it has exactly one trailing slash (“/”), while untrailingslashit will remove any trailing slashes from the string. These functions are mostly intended for use with file system paths, but work just fine with URLs and other strings.

Examples:

//Append a slash:
echo trailingslashit('/foo/bar');  // /foo/bar/
echo trailingslashit('/foo/bar/'); // /foo/bar/

//Remove slashes:
echo untrailingslashit('/foo/bar/);    // /foo/bar
echo untrailingslashit('/foo/bar////); // /foo/bar

size_format

function size_format( $bytes, $decimals = 0 );

Format an amount of data expressed in bytes using the largest suitable unit (e.g. kilobytes, megabytes, and so on). Set $decimals to the number of digits after the decimal point that you want to display.

This function is useful when you need to display file size or the amount of data transferred to the user.

Example:

$sizes = array(10, 1024, 2000000, 5000000000);
foreach($sizes as $size) {
	printf(
		'%s (%.0f bytes)',
		size_format($size, 2),
		$size
	);
}

Output:

10.00 B (10 bytes)
1.00 kB (1024 bytes)
1.91 MB (2000000 bytes)
4.66 GB (5000000000 bytes)

wp_ext2type

function wp_ext2type( $ext );

Guess the file type based on the extension. For example, this function will return “audio” for files that have the “.mp3” extension and “document” for “.pdf” files. Here’s a full list of the possible return values:

  • audio
  • video
  • document
  • spreadsheet
  • interactive
  • text
  • archive
  • code

Note that wp_ext2type does not check the contents of the file, only the extension.

Miscellaneous Functions

human_time_diff

function human_time_diff( $from, $to = '' );

Get difference between two timestamps in a human readable format such as “10 mins”, “1 hour” or “5 days”. If you omit the $to timestamp, it will return the difference between $from and the current time.

This example will print the titles of the last 5 posts and how long ago they were posted:

$posts = get_posts();
foreach($posts as $post) {
	printf(
		'"%s" was posted %s ago.',
		$post->post_title,
		human_time_diff(strtotime($post->post_date))
	);
}

wp_is_mobile

function wp_is_mobile()

Check if the current visitor is using a mobile device (smart phone, tablet, etc). Returns true for mobile users, false for everyone else.

status_header

function status_header( $http_status_code );

Send an HTTP status header with the specified status code. status_header() will automatically determine the HTTP protocol version in use and the status text to go with the status code.

For example, the following two lines are equivalent:

status_header(404);
header('HTTP/1.1 404 Not Found', true, 404);

li

Related posts :

15 Responses to “20+ Useful But Often Overlooked Utility Functions In WordPress”

  1. Ben May says:

    GREAT post. Thanks. A few new ones for me!

  2. Cool post, lots of new stuff learned.

  3. Silvan Hagen says:

    Great post thanks for that! There are couple of handy functions I didn’t know about yet.

  4. […] already has a number of built-in __return_* functions for when you need a callback that simply returns a predefined value. However, they only cover the […]

  5. […] I have written a lot of code in the past that could easily be substituted with a function or procedure that is already embedded in the core. If only I knew it was there… Browse through the core files (as stated in my previous commandment) and figure out how these all work. You will be amazed with what you can find in there. Like these utility functions. […]

  6. […] No reiventes la rueda, antes de escribir código aprende si hay una función o procedimiento que ya esté en el “core”. Aprende del “core”, como he apuntado antes, y descubre como funciona todo. Te sorprenderá todo lo que vas a encontrar ahí. Unos ejemplos serían estas funciones de utilidad. […]

  7. […] No reiventes la rueda, antes de escribir código aprende si hay una función o procedimiento que ya esté en el “core”. Aprende del “core”, como he apuntado antes, y descubre como funciona todo. Te sorprenderá todo lo que vas a encontrar ahí. Unos ejemplos serían estas funciones de utilidad. […]

  8. […] No reiventes la rueda, antes de escribir código aprende si hay una función o procedimiento que ya esté en el “core”. Aprende del “core”, como he apuntado antes, y descubre como funciona todo. Te sorprenderá todo lo que vas a encontrar ahí. Unos ejemplos serían estas funciones de utilidad. […]

  9. Banago says:

    This is a totally awesome post. Thanks for this great list of functions. We, as WP developers, are very easily trapped into coming up with out own custom functions.

    Great post!

  10. […] Quando começamos a programar, é comum o fato de escrevermos linhas e linhas de códigos para realizar um função e depois descobrimos que tudo aquilo poderia ser realizado com um simples comando. Isso é algo que faz parte do aprendizado, e com o tempo nos acostumamos a utilizar esses “atalhos” para poupar tempo e claro, os possíveis erros. O WordPress possui inúmeras funções que facilitam nosso trabalho, e vale muito a penas explorá-las. Confira algumas delas clicando aqui. […]

  11. […] (המרובות…) כי גם בהן יש עוד מידע. ועל WP יש מאמר על פונקציות מסייעות. הוא מחלק את הפונקציות לכמה קטגוריות: שמחזירות ערך, […]

  12. […] No reiventes the wheel, before learning to write code if there is a function or procedure that is already in the “core”. Learn the “core”, as I said before, and discover how everything works. You’ll be surprised what you will find there. Some examples would be these utility functions . […]

  13. […] 20+ Useful But Often Overlooked Utility Functions In WordPress – Today I bring you 20+ handy built-in WordPress functions. Some of them you may already know and use every day, while others you’ve probably never heard of as they’re usually not mentioned in WP tutorials or even the WordPress Codex. […]

  14. […] No reiventes la rueda, antes de escribir código aprende si hay una función o procedimiento que ya esté en el “core”. Aprende del “core”, como he apuntado antes, y descubre como funciona todo. Te sorprenderá todo lo que vas a encontrar ahí. Unos ejemplos serían estas funciones de utilidad. […]

Leave a Reply