15 useful WordPress Functions you probably don’t know
While I was building my first premium WordPress Plugin – the Avia Feedback Box – I needed to solve quite a few problems I have never encounterd when creating themes. During my research I stumbled upon several really cool wordpress functions that I want to share with you.
WordPress Transient API
set_transient(), get_transient(), delete_transient()
This is a function set very similar to get_options() and update_options() which helps to easily store and retrieve data in your options database table. The big difference here is that you also pass a time parameter which acts as expiration date for the database entry.
Once the time has expired the data is removed. This is especially useful if you want to cache data or query results for a short amount of time. An example would be a twitter widget which retrieves data from the twitter api, but since twitter is down pretty often it would be wise to save that data for a few minutes. That also would speed up the site for subsqequent page requests since you don’t need to connect to an external API.
It works pretty easy: the function set_transient accepts 3 parameters:
set_transient($transient, $value, $expiration);
so saving a value to your database for an hour would look like this:
set_transient('the_name', $special_query_results, 60*60);
getting the value like this:
$value = get_transient('the_name');
http://codex.wordpress.org/Transients_API
WordPress “Cron Jobs”
wp_schedule_event(time(), 'hourly', 'my_schedule_hook');
Schedules a hook which will be executed by the WordPress actions core on a specific interval, specified by you. The action will trigger when someone visits your WordPress site, if the scheduled time has passed.
So if you want to execute some code on a regular base, like checking an RSS Feed, doing a database backup or reseting database values this function will do it for you. Unfortunatley its not as easy to use as transient but here is a short article on how it is done:
http://themocracy.com/2010/02/wp-cron-automating-scheduling/
http://codex.wordpress.org/Function_Reference/wp_schedule_event
WordPress HTTP API
wp_remote_get( $url, $args = array() );
An easy to use function if you want to retrieve the content of a Webpage. The function stores the result within an easily accessible array. Not only do you get the result content of the webpage, you also get header informations and response codes. This function is also capable of retrieving feed content which also makes it useful if you want to create a twitter plugin or an rss reader with wordpress.
http://codex.wordpress.org/HTTP_API
http://codex.wordpress.org/Function_API/wp_remote_get
Easily Fetch an RSS Feed with WordPress
$feed = fetch_feed( $uri );
fetch_feed is another simple wordpress method to get feed content. It also has the added benefit that it uses the SimplePie and FeedCache functionality for retrieval and parsing and automatic caching.
http://codex.wordpress.org/Function_Reference/fetch_feed
WordPress mail function
wp_mail() wp_mail( $to, $subject, $message, $headers, $attachments );
Example: $to = 'kriesi@gmail.com'; $subject = 'Hello Kriesi!'; $message = 'This message was sent by wordpress' $mail = wp_mail($to, $subject, $message); if($mail) echo 'Mail delivered';
An incredible useful and exceptional easy to use function that also allows you to send headers and attachments, allows plain text sending and html messages and quite a few other options!
http://codex.wordpress.org/Function_Reference/wp_mail
WordPress Human Time
human_time_diff( $from, $to )
A feature to mimic twitter like time display. Instead of outputting the time in a basic format you can display it like this:
Kriesi posted 13 hours ago
http://codex.wordpress.org/Function_Reference/human_time_diff
WordPress get comments
get_comments()
Sometimes its neccessary to retrieve the comments outside of the comments loop like I did with the Avia Feedback Box Plugin, where comments are displayed via ajax. This function helps you in doing so ;)
http://codex.wordpress.org/Function_Reference/get_comments
WordPress validation of strings
wp_kses($string, $allowed_html, $allowed_protocols);
wp_kses is a very usefull function when it comes to sanitizing untrusted user input. This function makes sure that only the allowed HTML element names, attribute names and attribute values plus only sane HTML entities will occur in $string.
http://codex.wordpress.org/Function_Reference/wp_kses
WordPress text transformation
wptexturize()
A text transformation function that converts commonly used strings into the typographical correct signs. Used for dashes, ellipsis etc and will also add typograpic quotes to certain phrases.
http://codex.wordpress.org/Function_Reference/wptexturize
wpautop()
The last text transformation tool on the list is used by wordpress to ad <p> tags to a string by replacing double <br/> tags
http://codex.wordpress.org/Function_Reference/wpautop
WordPress Shortcode API
add_shortcode(), do_shortcode()
add_shortcode() is an easy way to create macros for your post content. for example lets say you want to wrap some content inside the post area within a div with some additional classes and ids that allows you to create multiple columns. you could of course just switch to the html editor and enter
<div class='one_third'>Content goes here</div>
Easier and more convenient especially if you are dealing with customers who dont know html would be a shortcode solution within your functions.php file:
function column_shortcode( $atts, $content = null ) { return '<div class='one_third>' . $content . '</div>'; } add_shortcode('one_third_column', 'column_shortcode');
You could then use this shortcode in your post content:
[one_third_column]Content goes here[/one_third_column]
If you would like to nest shortcodes within each other you would need to make sure to add the do_shortcode method to your function like this:
column_shortcode( $atts, $content = null ) { return '<div class='one_third>' . do_shortcode($content) . '</div>'; }
http://codex.wordpress.org/Shortcode_API
Create WordPress post with a php function:
wp_insert_post()
This function inserts posts pages and custom post types in the database. It sanitizes variables, does some checks, fills in missing variables like date/time, etc. very handy when you need to create and insert posts by user input. This function fits perfectly if you have a front end form for example and users can suggest posts.
http://codex.wordpress.org/Function_Reference/wp_insert_post
Create WordPress comment with a php function:
wp_insert_comment()
Similar to wp_insert_posts this function inserts a comment. Might also come in handy ;)
http://codex.wordpress.org/Function_Reference/wp_insert_comment
WordPress Object Cache:
wp_cache_add(), wp_cache_set(), wp_cache_get(), wp_cache_delete, wp_cache_replace(), wp_cache_flush
WP_Object_Cache is WordPress’ class for caching data which may be computationally expensive to regenerate, such as the result of complex database queries. If you care for theme and plugin performance you should definitley read the wordpress codex entry for this topic!
http://codex.wordpress.org/Function_Reference/WP_Cache
Kill wordpress execution:
wp_die()
An appropriate end for this post: the wp_die function
wp_die kills the WordPress execution and display HTML message with error message.
A call to this function complements the die() PHP function. The difference is that HTML will be displayed to the user. It is recommended to use this function only when the execution should not continue any further.
http://codex.wordpress.org/Function_Reference/wp_die
This is really a great set of functions. I have come across most of them, but it’s always nice to read them in a well-presented list.
Keep up the good work Kriesi.
thx for sharing ;)
Please tell me why [one_third_column]Content goes here[/one_third_column] is better than Content goes here
ok this wont let me paste html tags
Already wrote that in the post above ;)
If you want to publish a theme for example you cant be sure that people use correct html syntax. Also this is a very simple shortcode example, in my themes I use some that are as easy to use as the example above, yet produce image slideshows, toggles and tabs powered with javascript:
https://kriesi.at/themes/avisio/a-little-about-you/advanced-shortcodes/
Very nice list.
I like the “WordPress Shortcode API” Thing. Did not know that. That makes things sometimes easier.
I worked with several templates, but this is better :-)
Thank You!
Nice list, most of which I haven’t used but will be now. Also love the Josef Sans, Google Fonts Rock!
Very nice, thanks for sharing.
very nice tutorial. Thanks for sharing :)
Nice title, nice flow from your content, nice function and it’s nice to know you. Thanks for sharing to open my mind *ready to jailbreak!
wow! thanks for tips. this will be really helpful
Amazing list :) thanks for sharing.. need to try one by one
thank you! i really don’t know such function exists in wordpress. Thanks for this post.
Great place to learn.
Wow, tolle Seite, tolle Themes. Wieso kannte ich Deine Seite noch nicht? Werde jetzt öfters vorbeischauen! Vielen Dank für’s teilen.
Brilliant facts for upload files for getting myself personally get going. Most definitely i’ll keep this particular website link and return to this.
Very informative article thank for the tips
Thanks for this great article.
Thierry, a french reader
Wow, very useful article. thanks.
Great article! Using these functions will save me some lines of code instead of re-implementing my own functions in PHP. The chron job and object cache functions seem really useful.
Great functions, very useful!!!. Thanks Kriesi!!!! :D
effective, thanks
Guten Tag Ihr Musikhörer. Es gibt eine erstklassige Webseite bei der alle umsonst richtige Partytracks downloaden könnt! Ihr könnt direkt auf http://www.party-hits.org/packets/PartyMix_part1.rar gehen und euren Partytrack ziehen. Finde ich schon super nice. Ist wirklich mein Megatipp für 2010 !!!