15 Useful WordPress Functions All Developers Should Know

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.

antispambot()

I usually raise a few eyebrows with this one, it seems to be one of the most well-hidden functions in the codebase. <code>antispambot()</code> replaces characters with HTML entities which is one way to mask email addresses from evil scrapers.

$email = 'mymail@mail.com';
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.

human_time_diff()

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

get_post_meta()

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 <code>get_post_meta()</code> 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.

wp_upload_bits()

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 <code>wp_insert_attachment()</code> function.

$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.

get_post_field()

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 <code>get_post_field()</code>. 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 <?php echo get_post_field( 'comment_count', 4124 ) ?> comments.

wpautop()

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.

<h2>What Our Users Say</h2>
<?php echo wpautop( $user_comment ) ?>

wp_is_mobile()

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.

<?php if( wp_is_mobile() ) : ?>
Visit our website on your desktop for a richer user experience
<?php endif ?>

wp_redirect()

The last example shows another neat function: <code>wp_redirect()</code>. This should be used in place of the PHP native <code>header()</code> 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 );

paginate_links()

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 <code>paginate_links()</code> 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
) );

wp_die()

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

has_block()

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.

<?php
if ( has_block() ) {
    // Content has a block.
} ?>

wp_set_script_translations()

Since many part of WordPress user interface is going to move to JavaScript, it needs a convenient way to register translatable texts in the JavaScript that WordPress could parse and understand. Use this function to set translated strings for your scripts. Below is an example:

wp_enqueue_script( 'my-script', plugins_url( 'js/my-script.js', __FILE__ ) );
wp_set_script_translations( 'my-script', 'mu-text-domain' );

register_block_type()

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

rest_do_request()

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() : [];

rest_preload_api_request()

When building a JavaScript-heavy UI in WordPress typically needs a set of initial data proloaded within the page. This is the function that will allow you to do so. This function is meant to be used in conjunction with the 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'
);

Conclusion

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!

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail