7 Overlooked WordPress Helper Functions
Code reuse is key to solid development. When developing large-scale WordPress plugins and themes you are bound to write helper functions to solve certain tasks. WordPress has around 10,000 functions in its core so the probability that a helper function that you’re about to write already exists could be quite high.
size_format( $bytes, $decimals = 0 )
Converts bytes to human readable sizes – kb, MB, GB, TB followed by a number of
$decimals. Defined in wp-includes/functions.php.
There is actually a second function available in wp-admin/includes/template.php, which does almost the same in a different way.
wp_convert_bytes_to_hr(), available the administration panel context. Ticket #19067 attempts to get rid of this redundancy.
maybe_unserialize( $orginal )
wp_check_filetype( $filename, $mimes = null )
Defined in wp-admin/includes/template.php. Check the filetype of any accessible file. Returns an associative array containing the extension and the detected filetype. Detection is based on extensions only, so don’t expect it to detect using file header signatures.
WP_Http_Encoding::compress/decompress( $data )
Part of the HTTP API, defined in wp-includes/class-http.php. Compression
gzdeflate()s data, takes optional
$level argument. Decompression attempts to inflate, using a variety of methods. These are useful for storing large unsearchable binary data in the database or in files.
Next time you start coding your own error containers (Objects, Arrays, Exceptions, etc.), you can use WP_Error instead. Contains simple to use methods to store and retrieve errors messages and codes wrapped in a compact, mobile and inheritable class. Don’t hesitate to read the source code.
Argument list is
wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ). Highly useful for generating random data. Is a pluggable function, defined in wp-includes/pluggable.php. If you’re feeling adventurous, check the
wp_rand( $min = 0, $max = 0 ) function defined a little lower. Don’t wholeheartedly rely on pluggables, though, they can be overridden.
get_avatar( $id_or_email )
Another highly useful pluggable function used to get Gravatar for any WordPress user_id or e-mail. Although the Gravatar API is very simple, WordPress makes it even simpler. Defined in wp-includes/pluggable.php. Again, don’t rely on pluggables unless you know they’ve not been fiddled with by other plugins.
So next time you catch yourself writing a helper function, ask yourself the following question: “Doesn’t WordPress do this already?”
Have you found any other useful functions in the source that are being overlooked? Like formatting functions?