WordPress is full of great functions for us developers to use. We can pull post lists out of thin air, manipulate almost everything about them, grab any user we wish and display their social media connections in a jiffy.
There are however quite a few functions which seem to be overlooked for unknown reasons. I’ve been coding with WordPress for around 8 years now and occasionally I still find something new! Let’s take a look at some of my favourite overlooked functions and learn how to use them along the way.
Recommended Reading: WordPress Conditional Tags (And Snippets) For Beginners
I usually raise a few eyebrows with this one, it seems to be one of the most well-hidden functions in the codebase.
replaces characters with HTML entities which is one way to mask email addresses from evil scrapers.
$email = '[email protected]'; echo 'You can contact me at ' . antispambot( $email ) . ' any time'.
While this is a useful tidbit, it is also an example of why some people criticise WordPress – this is a horribly named function. From reading the function name, you have no idea what it does.
When I first learned about this function about a year ago I thought it must have been a recent addition which I overlooked in a changelog. Not quite…
This function – which outputs the difference between two timestamps – has been in since version 1.5 (that’s February 17, 2018!).
The following great snippet I borrowed from the codex shows how long ago a current post was published. It uses the publish date of the post as the first argument and the current date as the second.
echo 'This post was published ' . human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) . ' ago';
Bear with me here, I know this is a well-used function, however, how it works is not-so-common knowledge. First of all, by omitting the second and third parameters you can pull all metadata for a post.
$all_meta = get_post_meta( 14 );
Even if you only grab the data for a single key all postmeta is pulled anyway.
The reason is actually pretty logical. Metadata is used in multiple places. If
queries the database each time it was used we would end up with way too many queries. Instead, if you pull metadata it caches it all and uses the cached values on all subsequent metadata retrievals.
This function is a straight-up file uploading function. While it doesn’t move the file to the uploads folder and add it to the WordPress media section, it is extremely convenient and you can always do the rest with the
$upload = wp_upload_bits( $file['name'], null, file_get_contents( $file['tmp_name'] ) );
Some explanation is at hand for this: the first parameter is the file name. The second is depreciated so it should be set to null (eyeroll at WordPress consistency). The third parameter is the actual content of the file.
In the past I saw quite a few examples where someone wrote a loop to get a comment count for a post, or wrote a dedicated database query for it. You don’t need them, what you need is
. This function retrieves the value of a single field for a single post in the database. Let’s grab a comment count!
This post has comments.
This function has come out into the spotlight a bit, but it is still relatively unknown. It is similar to the PHP native
nl2br but instead of creating new lines, it wraps your content in paragraphs.
This is useful if you have a textbox and you want to make sure that when users create paragraphs with double line breaks, they remain visible in the front-end as well.
What Our Users Say
This aptly named function detects when a user is on a mobile device and allows you to display content accordingly. Since this is a conditional tag it returns true or false depending on the scenario.
Visit our website on your desktop for a richer user experience
The last example shows another neat function:
. This should be used in place of the PHP native
header() function. The WordPress redirection function allows you to set a URL to redirect to, and also set a status code, great for handling permanent redirects as well.
// For a URL which is no longer in use wp_redirect( 'http://website.com/new-url/', 301 );
I bet that this function owes its obscurity in part to the popularity of the WP-PageNavi plugin. By default WordPress displays previous/next links at the end of your post list. WP-PageNavi replaces that with page numbers.
This can actually be done with a little work using the
functions. It has quite a few parameters so I recommend taking a peek at the documentation.
The following example from the codex shows how you can add it to a default loop but adding it to custom loops is not much of a stretch.
global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages ) );
This function complements the PHP
die() function. The difference is that this function will display a WordPress-styled HTML instead of just a plain text. You can use this function to stop PHP execution. You can add the message, title, and additional arguments to be displayed, for example:
wp_die( "Oops, you don't have access to the", "Permission Denied" );
In version 5.0, WordPress introduced a block based editor, codenamed Gutenberg. This function will identify whether the the content contains a Gutenberg, quite the same with the
has_shortcode() function. It’ll return
true if the content does contain a block, or
false if it does not.
wp_enqueue_script( 'my-script', plugins_url( 'js/my-script.js', __FILE__ ) ); wp_set_script_translations( 'my-script', 'mu-text-domain' );
Another prominent function in WordPress 5.0. This function allows you to register a new block in the new WordPress editor. Your block will appear in the new editor and insert it .
register_block_type( 'my-plugin/new-block', array( 'title' => 'New Block', 'icon' => 'megaphone', 'category' => 'widgets', 'render_callback' => 'render_function_callback', ) );
This function allows you to make a call to WordPress REST API endpoints through PHP. Pretty useful when you need to retrieve an output from the REST API to process that you’ll process further within the PHP side instead of in the browser (front-end) side.
$request = new WP_REST_Request( 'GET', "/wp/v2/posts" ); $request->set_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) ); $response = rest_do_request( $request ); $data = 200 === $response->get_status() ? $response->get_data() : ;
array_reduce, for example.
// Preload common data. $preload_paths = array( '/', '/wp/v2/types?context=edit', '/wp/v2/taxonomies?per_page=-1&context=edit', '/wp/v2/themes?status=active', ); preload_data = array_reduce( $preload_paths, 'rest_preload_api_request', array() ); wp_add_inline_script( 'wp-api-fetch', sprintf( 'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );', wp_json_encode( $preload_data ) ), 'after' );
These are just some functions that seem to be less-known that the rest. I discover a new great function about every two months and I’m sure my developer friends out there could surprise us even further.
If you have a favorite obscure function or a function which would be useful but isn’t available, let us know in the comments!
The post 15 Useful WordPress Functions All Developers Should Know appeared first on Hongkiat.WordPress Website Development