Three Awesome Functions in WordPress You Might Not Know About

WordPress is a large application. According to Westi’s XREF of trunk, WordPress defines 188 classes, 3840 functions, and 302 constants (since the xref counts variables of all scopes, I’m not including them here). For comparison, depending on your version of PHP, there are anywhere from 2-4 thousand native functions in the language. With so many functions, WordPress is bound to have some really cool ones floating around; and unless you either read core or are active on trac and/or #wordpress-dev, you might not have seen these before.

checked/selected/disabled

I’m counting these as one function, since they’re really just wrappers for the same function, __checked_selected_helper(). Basically, you use these in forms for checkbox, radio, and select items, or anything that you might need to disable. Each function takes three arguments (I’ll be using checked, but the other two are used the same way). Examples to follow.

checked( $value_of_some_option, $value_of_this_checkbox = true, (bool)$whether_to_echo = true );
  1. $value_of_some_option (mixed): This is the value that will determine whether the box is checked. It should be treated as an unknown variable. This is also the only required argument in all three of these functions.
  2. $value_of_this_checkbox (mixed): This argument defaults to the boolean true. This is the value of the current item you’re checking for. These functions check if the first and second arguments are identical (three equals signs). If so, the function returns the checked/selected/disabled attribute; otherwise it returns an empty string.
  3. $whether_to_echo (boolean): This argument defaults to true. These functions will always return the produced string. If this argument returns true (so non-empty strings, arrays, etc. will also work for this purpose), the function will also echo the produced string.

So here’s how to use these functions:

<!--?php<br /-->$my_option = get_option( 'jpb_awesome_option' );
$is_meh = get_option( 'jpb_not_awesome_just_meh' );
echo "<label><input name="jpb_awesome_option" type="radio" value="1" /> This is awesome.</label>";
?>
<label><input name="jpb_awesome_option" type="radio" value="0" /> This is just "meh".</label>
<label>How "meh" is it?
<select name="jpb_not_awesome_just_meh">
<option>Just kidding, it's awesome.</option><option value="slighlty">It's only slightly "meh"</option><option value="very">This is Alot of "meh"</option></select>
</label>
<!--?php<br /-->

If they return a value, all three of these functions will include a space at the beginning of the return value, but not the end.

paginate_links

This one is more well known, especially if you’re a theme designer. It takes one argument, which is an array of arguments. This function creates a nice set of pagination links, with the option of having a first, previous, next, and last links, as well as X amount of links surrounding the current page
(e.g.:
« Prev 13 4 5 6 79 Next »
)
Here are the arguments, their defaults, and a quick explanation:

  • ‘base’ (default: '%_%'): The base url structure to use. Can be absolute or relative. Relative URLs will use the current page as the base. Keep in mind that this should have '%_%' in it somewhere, which will be replaced by the ‘format’ option below. (e.g.: http://example.com/all_posts.php%_%)
  • ‘format’ (default: '?page=%#%'): Adds the pagination structure. If you’re using pretty permalinks, this would be '/page/%#%'.
  • ‘total’ (default: 1): Total number of pages available. This must be greater than 1 to get any results from this function.
  • ‘current’ (default: 0): The current page number.
  • ‘show_all’ (default: false): Show all pages, not just those around the current page
  • ‘prev_next’ (default: true): Whether to show links for the next and previous pages.
  • ‘prev_text’ (default: '&laquo; Previous'): The text for the ‘previous page’ link.
  • ‘next_text’ (default: 'Next &raquo;'): The text for the ‘next page’ link.
  • ‘end_size’ (default: 1): How many links from the first and last page to show.
  • ‘mid_size’ (default: 2): How many links to show on each side of the current page.
  • ‘type’ (default: 'plain'): The format to return. 'plain' will return the links separated by newlines; 'list' will return the links in an unordered list (<ul>); 'array' will return the links as a keyed array.
  • ‘add_args’ (default: false): Allows you to add arguments to the formatted url.
  • ‘add_fragment’ (default: ''): This is the string appended to the end of each link.

The arguments array can be either an argument string or an associative array. So to get the link style above, I’d have to use the function like this:

echo paginate_links(array(
  'current' => 5,
  'total' => 9,
  'prev_text' => '« Prev'
));

wp_localize_script

wp_localize_script() is by far the most useful function that hardly anybody knows about. Basically, you take a standard queued script using wp_enqueue_script and feed it an associative array to print to the browser as a javascript object. Here’s how it works:

wp_localize_script( $handle_of_queued_script, $unique_name_for_js_object, $associative_array_to_become_object );

The first argument is the handle of the script you’d like to localize (e.g. 'jquery'). The second argument is the name of the javascript variable in which to store the object. This will be an object in the global namespace, so try to make it unique. The third argument is an associative array which will become the object. The purpose of this function is to allow you to localize/internationalize your plugin’s or theme’s scripts. For example, if you need to send an alert to the user if they click the delete button, you would write your javascript file like this:

jQuery(document).ready(function($){
  $('.alert-click').click(function(e){
    if( !confirm("Are you sure you want to do that?") ){
      e.preventDefault();
    }
  });
});

and then you would enqueue your javascript like this:

function no_accidental_deletes(){
  wp_enqueue_script( 'jpb-accidental', plugins_url( 'accidental.js', __FILE__ ), array( 'jquery' ), '1.0' );
}
add_action( 'template_redirect', 'no_accidental_deletes' );

But what if somebody wants to translate your plugin into German? 1 You can’t use WordPress’ gettext functions in javascript; this is where we localize the script. You would change your javascript to look like this:

jQuery(document).ready(function($){
  $('.alert-click').click(function(e){
    if( !confirm( NoAccidents.areYouSure ) ){
      e.preventDefault();
    }
  });
});

and your php to look like this:

function no_accidental_deletes(){
  wp_enqueue_script( 'jpb-accidental', plugins_url( 'accidental.js', __FILE__ ), array( 'jquery' ), '1.0.1' );
  wp_localize_script( 'jpb-accidental', 'NoAccidents', array( 'areYouSure' => __( 'Are you sure you want to do that?', 'my-gettext-domain' ) ) );
}
add_action( 'template_redirect', 'no_accidental_deletes' );

and voila! Your script is localized. Of course, this has practical benefits aside from translation. Any javascript variables that need to be generated on each pageload but should also fit correctly into the dependency tree that you get from wp_enqueue_script can be added using this.

What are your favorite hidden gems in the WordPress core?

Notes:

  1. Let’s pretend Germans don’t all speak English better than most Americans do.

Kansas boy transplanted to DC. English major transplanted to web development. Lover of things.

4 Comments

  1. Ozh · February 9, 2011

    Scanning the page, it took me a while to figure out what 3 functions you were referring to. I suggest using h2 instead of h3 and/or adding some style on headers 😉

    Oh, and, you win. I didn’t know about paginate_links(), probably because I almost never do theming 🙂

    • John P. Bloch · February 9, 2011

      Thanks, I hadn’t thought about that, since I knew where to look… 🙂

      paginate_links has saved me hours and hours of work. I actually learned about this function from Justin Tadlock’s theme framework Hybrid.

  2. Michael Fields · February 13, 2011

    Thanks for the post John! This is a perfect time to find out about paginate_links() as I am upgrading a plugin with paged taxonomy terms. This will save me more than a line or two! Keep up the good work 🙂

  3. Damian Gostomski · March 3, 2011

    Nice post.
    NNormally when you get the posts in the style “10 things you didn;t know about XYZ”, they seem to be the same things over and over again.

    Not sure how useful checked/selected/disabled is to me, as 99% of my form stuff goes through Gravity Forms and I knew about the pagination one, but the last one, wp_localize_script, is both new to me, and more importantly, useful.
    Not so much for localizing, but for allowing me to move strings out of my JS – Which is especially useful if you need to have lots of user specific data in there, or just want to be able to manage them all in a single place