Wednesday, December 10, 2014

10 Useful WordPress Functions You Might Not Know About

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, 2005!).


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 to 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 ?>

DOING_AJAX


While this is a constant, not a function (sorry), it is useful nonetheless. You can discern between AJAX calls and regular stuff by checking if it is defined and is true. This can be useful if you are using a common function for a task that is sometimes triggered by AJAX.



if (defined("DOING_AJAX") && DOING_AJAX)
echo "done";
die()

else

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

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!



10 Useful WordPress Functions You Might Not Know About

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.