Some Useful Small Built-In Functions In WordPress

Some Useful Small Built-In Functions In WordPress
Some Useful Small Built-In Functions In WordPress

If you look into the code of Meta Box Script, you’ll see I use functions checked, selected many times to add attributes into form elements. They’re helper functions that have built-in WordPress. There’re several of them listed in wp-includes/functions.php file. In this post, we’ll look at some typical ones.

Return Functions

Sometimes you only want a function that returns a very simple value such as true, zero or an empty array. Here they are:

// Returns true
function __return_true() {
 return true;
}

// Returns false
function __return_false() {
 return false;
}

// Returns 0
function __return_zero() {
 return 0;
}

// Returns an empty array
function __return_empty_array() {
 return array();
}

A very popular hack that using one of these functions is removing admin bar in WordPress 3.1, it looks like:

add_filter('show_admin_bar', '__return_false');

Form Helper Functions

There’re 3 form helper functions: selected, checked, diabled:

// Outputs the html checked attribute.
function checked( $checked, $current = true, $echo = true );

// Outputs the html selected attribute.
function selected( $selected, $current = true, $echo = true );
// Outputs the html disabled attribute.
 function disabled( $disabled, $current = true, $echo = true );

These functions use the same technique: they compares the first two arguments and if identical marks as selected, checked or diabled.

In the code of Meta Box Script, I used the checked for radio input like this:

echo "<input type='radio' name='{$field['id']}' value='$key'" . checked($meta, $key, false) . " /> $value ";

Using this function helped me save a lot of time writing checking conditional like this:

echo "<input type='radio' name='{$field['id']}' value='$key'" . ($meta == $key ? " checked='checked'" : "") . " /> $value ";

If you’re working with form, and if your form has many fields, these functions will help you (really) keep your code cleaner.

4 thoughts on “Some Useful Small Built-In Functions In WordPress

  1. What is te benefit of using add_filter(‘show_admin_bar’, ‘__return_false’); instead of add_filter(‘show_admin_bar’, false); ?

    I don’t see the point of having a funtion for this!?

    1. add_filter(‘show_admin_bar’, false);
      I don’t think this is a correct way to use add_filter, you will get a php warning ‘First argument is expected to be a valid callback’.

Comments are closed.

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

Want to get away from Pipdig drama? See 30+ Pipdig blog themes alternatives See here →