Deluxe Blog Tips About Projects

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.

Subscribe to the Newsletter

Subscribe to get my latest content by email. I won't send you spam. Unsubscribe at any time.