<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:series="http://unfoldingneurons.com/" version="2.0">

<channel>
	<title>Wptuts+</title>
	
	<link>http://wp.tutsplus.com</link>
	<description>WordPress Tutorials</description>
	<lastBuildDate>Sat, 02 Jun 2012 11:00:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Wptuts" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="wptuts" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">Wptuts</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>How to Make a Radio Station Schedule Using WordPress</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/how-to-make-a-radio-station-schedule-using-wordpress/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/how-to-make-a-radio-station-schedule-using-wordpress/#comments</comments>
		<pubDate>Sat, 02 Jun 2012 11:00:39 +0000</pubDate>
		<dc:creator>Kailan Wyatt</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[Custom Post Types]]></category>
		<category><![CDATA[post thumbnails]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25555</guid>
		<description><![CDATA[<p>Often enough, many radio stations are built using WordPress, but many don&#8217;t harvest the true potential to create a true online radio station. This tutorial will demonstrate how you can turn a radio website into a fully functional radio station DJ listing with a nifty radio schedule for featured shows.<span id="more-25555"></span></p>
<hr />
<h2>Introduction</h2>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/286_How_to_Make_a_Radio_Station_Schedule_Using_WordPress/result.jpg" border="0" /></div>
<p>For our online radio website, we will feature some DJ&#8217;s/hosts that play on the air. We will create a custom post type for them, where we can add a picture, biography and other useful information. We will also create a show schedule using the WordPress custom post type again. Mixed with some custom metaboxes, we&#8217;re going to make the show administration simple to manage.</p>
<hr />
<h2><span>Step 1</span> Creating DJ/Host Custom Post Type</h2>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/286_How_to_Make_a_Radio_Station_Schedule_Using_WordPress/dj_post_type.jpg" border="0" /></div>
<p>To avoid files cluttered with code, we&#8217;ll separate our snippets and by using the PHP function <code>include</code>, we&#8217;ll include them to our file. Open your <strong>functions.php</strong> file, located in your current theme folder and add the following snippet:</p>
<pre name="code" class="php">
include('schedule.php');
</pre>
<p>Once complete, create a new file called <strong>schedule.php</strong>, then we add our functions to register our new post type.</p>
<blockquote><p><em>For more information on custom post types, try this page <a href="http://wp.tutsplus.com/tag/custom-post-types/" target="_blank">custom post type</a></em></p>
</blockquote>
<pre name="code" class="php">
// Register DJs Post Type
add_action( 'init', 'register_my_radios_djs' );

function register_my_radios_djs() {
	$labels = array(
		'name' =&gt; _x( 'Radio Djs', 'radios_djs' ),
		'singular_name' =&gt; _x( 'Radio Dj', 'radios_djs' ),
		'add_new' =&gt; _x( 'Add New', 'radios_djs' ),
		'add_new_item' =&gt; _x( 'Add New Dj', 'radios_djs' ),
		'edit_item' =&gt; _x( 'Edit Dj', 'radios_djs' ),
		'new_item' =&gt; _x( 'New Dj', 'radios_djs' ),
		'view_item' =&gt; _x( 'View Dj', 'radios_djs' ),
		'search_items' =&gt; _x( 'Search Dj', 'radios_djs' ),
		'not_found' =&gt; _x( 'No dj  found', 'radios_djs' ),
		'not_found_in_trash' =&gt; _x( 'No dj  found in Trash', 'radios_djs' ),
		'parent_item_colon' =&gt; _x( 'Parent Dj:', 'radios_djs' ),
		'menu_name' =&gt; _x( 'Radio Djs', 'radios_djs' )
	);
	$args = array(
		'labels' =&gt; $labels,
		'hierarchical' =&gt; true,
		'description' =&gt; 'WordPress Radio DJS',
		'supports' =&gt; array( 'title', 'editor', 'thumbnail' ),
		'taxonomies' =&gt; array( 'category', 'radios_djs' ),
		'public' =&gt; true,
		'show_ui' =&gt; true,
		'show_in_menu' =&gt; true,
		'show_in_nav_menus' =&gt; true,
		'publicly_queryable' =&gt; true,
		'exclude_from_search' =&gt; false,
		'has_archive' =&gt; true,
		'query_var' =&gt; true,
		'can_export' =&gt; true,
		'rewrite' =&gt; true,
		'capability_type' =&gt; 'post'
	);

	register_post_type( 'radios_djs', $args );
}
</pre>
<h3>Adding Post Thumbnails</h3>
<p>For this tutorial, we will be using formatted images for the schedule. Therefore, we&#8217;re going to add the WordPress post thumbnail functionality.</p>
<pre name="code" class="php">
if ( function_exists( 'add_theme_support' ) ) {
	add_theme_support( 'post-thumbnails' );
	set_post_thumbnail_size( 150, 150, true );
	add_image_size( 'dj-pic', 260, 160 );
}
</pre>
<p>Notice that we&#8217;ve added the function <code>add_image_size</code> and some parameters. We&#8217;ll be using the post thumbnail size of 260&#215;160 for our end result.</p>
<hr />
<h2><span>Step 2</span> Creating Schedule Custom Post Type</h2>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/286_How_to_Make_a_Radio_Station_Schedule_Using_WordPress/schedule_post_type.jpg" border="0" /></div>
<p>Just like the previous step, we&#8217;re going to create a next post type using the same method and simply changing some names and variables.</p>
<pre name="code" class="php">
// Register Schedule Post Type
add_action( 'init', 'register_my_dj_schedule' );

function register_my_dj_schedule() {

	$labels = array(
		'name' =&gt; _x( 'Dj Schedule', 'dj_schedule' ),
		'singular_name' =&gt; _x( 'Dj Schedule', 'dj_schedule' ),
		'add_new' =&gt; _x( 'Add New', 'dj_schedule' ),
		'add_new_item' =&gt; _x( 'Add New Schedule', 'dj_schedule' ),
		'edit_item' =&gt; _x( 'Edit Dj Schedule', 'dj_schedule' ),
		'new_item' =&gt; _x( 'New Dj Schedule', 'dj_schedule' ),
		'view_item' =&gt; _x( 'View Dj Schedule', 'dj_schedule' ),
		'search_items' =&gt; _x( 'Search Dj Schedule', 'dj_schedule' ),
		'not_found' =&gt; _x( 'No dj schedule found', 'dj_schedule' ),
		'not_found_in_trash' =&gt; _x( 'No dj schedule found in Trash', 'dj_schedule' ),
		'parent_item_colon' =&gt; _x( 'Parent Dj Schedule:', 'dj_schedule' ),
		'menu_name' =&gt; _x( 'Dj Schedule', 'dj_schedule' )
	);

	$args = array(
		'labels' =&gt; $labels,
		'hierarchical' =&gt; true,
		'description' =&gt; 'WordPress DJ Schedule',
		'supports' =&gt; array( 'title', 'editor', 'thumbnail' ),
		'taxonomies' =&gt; array( 'category', 'dj_schedule' ),
		'public' =&gt; true,
		'show_ui' =&gt; true,
		'show_in_menu' =&gt; true,
		'show_in_nav_menus' =&gt; true,
		'publicly_queryable' =&gt; true,
		'exclude_from_search' =&gt; false,
		'has_archive' =&gt; true,
		'query_var' =&gt; true,
		'can_export' =&gt; true,
		'rewrite' =&gt; true,
		'capability_type' =&gt; 'post'
	);

	register_post_type( 'dj_schedule', $args );
}
</pre>
<hr />
<h2><span>Step 3</span> Adding Custom Meta Boxes</h2>
<p>This tutorial won&#8217;t explain every aspect of creating custom metaboxes, but we&#8217;ll highlight the most significant. With that said, we&#8217;ll begin by calling two <code>add_action</code> hooks for our metaboxes.</p>
<pre name="code" class="php">
add_action( 'add_meta_boxes', 'rschedule_box' );
add_action( 'save_post', 'dj_schedule_save_postdata' );
</pre>
<blockquote><p><em>In you&#8217;re interested in learning more about custom meta boxes. This is a great read: <a href="http://wp.tutsplus.com/tutorials/plugins/how-to-create-custom-wordpress-writemeta-boxes/" target="_blank">How to Create Custom WordPress Write/Meta Boxes</a></em></p>
</blockquote>
<h3>Add the Meta-Boxes</h3>
<p>The function <code>rschedule_box</code> which was previously mentioned in the hook, will register a group of metaboxes to our post edit screen. We will use these metaboxes on our Schedule Edit page.</p>
<pre name="code" class="php">
function rschedule_box() {
	add_meta_box(
		'time_slot_id',
		__( 'Time Slots', 'time_slot_text' ),
		'radio_time_slots',
		'dj_schedule'
	);
	add_meta_box(
		'dj_select_id',
		__( 'Select DJ', 'dj_select_text' ),
		'radio_get_dj_select_box',
		'dj_schedule',
		'side'
	);
}
</pre>
<h3>Creating a DJ Select List</h3>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/286_How_to_Make_a_Radio_Station_Schedule_Using_WordPress/dj_select.jpg" border="0" /></div>
<p>In this step, we create a function that will generate a select list on our screen. This list will display all the DJs/Hosts added to our custom post type, that we created in Step 1. This function will query the post type and return the items as an array, then we will loop though the array and mix it with some HTML. This way, we can reference the DJ post ID, which we will need in generating our output later.</p>
<pre name="code" class="php">
function radio_get_dj_select_box($post) {
	wp_nonce_field( 'radio_schedule', 'schedule_noncename' );
	echo '&lt;label for="dj_id"&gt;';
	_e("DJ/Host", 'dj_id' );
	echo '&lt;/label&gt; ';
	$args = array( 'post_type' =&gt; 'radios_djs');
	$loop = new WP_Query( $args );
	echo '&lt;select name="dj_id" id="dj_id"&gt;';
	foreach ( $loop-&gt;posts as $dj ) {
		if ( $dj-&gt;ID == get_post_meta( $post-&gt;ID, 'dj_id', true ) ) {
			$select = 'selected';
		}
		else {
			$select = '';
		}
		echo '&lt;option value="'.$dj-&gt;ID.'" '.$select.'&gt;'.$dj-&gt;post_title.'&lt;/option&gt;';
	}
	echo '&lt;/select&gt;';
}
</pre>
<h3>Creating Time Slots</h3>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/286_How_to_Make_a_Radio_Station_Schedule_Using_WordPress/time_slot.jpg" border="0" /></div>
<p>The next function is our function that will display the days of the week and options to choose the time when the show will be live. In order for us to get the days of the week, we&#8217;ll create an array.</p>
<pre name="code" class="php">
$days = array(
	'sun' =&gt; 'Sunday',
	'mon' =&gt; 'Monday',
	'tue' =&gt; 'Tuesday',
	'wed' =&gt; 'Wednesday',
	'thu' =&gt; 'Thursday',
	'fri' =&gt; 'Friday',
	'sat' =&gt; 'Saturday'
);
</pre>
<p>Now that&#8217;s done, let&#8217;s create our time slot function. Add the following code to your file.</p>
<pre name="code" class="php">
/* Prints the box content */
function radio_time_slots($post) {

	global $days;
	// Use nonce for verification
	wp_nonce_field( 'radio_schedule', 'schedule_noncename' );

	foreach ( $days as $key =&gt; $value ) {
		$selected_start  = get_post_meta( $post-&gt;ID, 'schdule_dj-start-'.$key, true );  //Start Time
		$selected_end  = get_post_meta( $post-&gt;ID, 'schdule_dj-end-'.$key, true );  	  //End Time

		echo '&lt;strong&gt;'.$value.'&lt;/strong&gt;&lt;br /&gt;';
		echo '&lt;label for="schdule_dj-start-'.$key.'"&gt;';
		_e("Start", 'schdule_dj-start-'.$key );
		echo '&lt;/label&gt; ';
		echo '&lt;select name="schdule_dj-start-'.$key.'" id="schdule_dj-start-'.$key.'"&gt;';
		schedule_time_select($selected_start);
		echo '&lt;/select&gt;';
		echo '&lt;label for="schdule_dj-end-'.$key.'"&gt;';
		_e("End", 'schdule_dj-end-'.$key );
		echo '&lt;/label&gt; ';
		echo '&lt;select name="schdule_dj-end-'.$key.'" id="schdule_dj-end-'.$key.'"&gt;';
		schedule_time_select($selected_end);
		echo '&lt;/select&gt;';
		echo '&lt;br /&gt;';
	}
}
</pre>
<p>As you will notice we referenced our array of days by using <code>global $days</code>. We could have placed it inside of the function but we will be referencing it occasionally, so we&#8217;ll leave it on the outside. Also, take a look at how the array of days is used, we have chosen to loop some select fields using the days, so we should have several select fields for the 7 days of the week. The variables <code>$selected_start</code> and <code>$selected_end</code> use the WordPress function <code>get_post_meta</code>, in order to get the currently selected value for our list. We are also strategically using the <code>key</code> of our array in our list to name our form field, label and get our selected value. When PHP interprets the field name, it will look similar to this <code>schdule_dj-start-sun</code> where <code>sun</code> will be changed according to the current day in the loop. This will be quite useful to us in other parts of the tutorial. Lastly, you will realise that we&#8217;ve referenced the function <code>schedule_time_select</code>, that we have not created as yet. Let&#8217;s create that function now.</p>
<pre name="code" class="php">
function schedule_time_select($selected) {
	$start = 8*60+0;
	$end = 24*60+0;
	echo '&lt;option vlaue="0"&gt;N/A&lt;/option&gt;'; //Default Value
	for($time = $start; $time&lt;=$end; $time += 15) {
		$minute = $time%60;
		$hour = ($time-$minute)/60;
		if ( $selected == sprintf( '%02d:%02d', $hour, $minute ) ) {
			$select = 'selected';
		}
		else {
			$select = '';
		}
		echo '&lt;option value='.sprintf('%02d:%02d', $hour, $minute).' '.$select.'&gt;'.sprintf('%02d:%02d', $hour, $minute).'&lt;/option&gt;';
	}
}
</pre>
<p>This function will generate the options for our select list. Each option will be incremented by 15 minutes and is based on the the 24 hour system. For the first option, we set a value of <code>0</code> for the days that we wish to neglect. Within the loop, there is a small <code>if</code> statement that checks the value sent from our radio time slot function to determine if the option should be set to selected.</p>
<hr />
<h2><span>Step 3</span> Saving the Meta Boxes</h2>
<p>Finally, it&#8217;s time to save all of our metabox information. WordPress has a very simple and straight forward way of saving these options but we&#8217;re going to make it more dynamic. Add the following snippet to your file.</p>
<pre name="code" class="php">
// Save Meta Data
function dj_schedule_save_postdata( $post_id ) {
	if ( defined( 'DOING_AUTOSAVE' ) &#038;&#038; DOING_AUTOSAVE )
		return;

	if ( !wp_verify_nonce( $_POST['schedule_noncename'], 'radio_schedule' ) )
		return;

	if ( 'page' == $_POST['post_type'] ) {
		if ( !current_user_can( 'edit_page', $post_id ) )
			return;
	}
	else {
		if ( !current_user_can( 'edit_post', $post_id ) )
			return;
	}

	if( isset( $_POST['dj_id'] ) ) {
		update_post_meta( $post_id,'dj_id', esc_attr( $_POST['dj_id'] ) );
	}

	global $days;

	foreach($days as $key=&gt;$value) {

		if( isset( $_POST['schdule_dj-start-'.$key] ) ) {
			update_post_meta( $post_id,'schdule_dj-start-'.$key, esc_attr( $_POST['schdule_dj-start-'.$key] ) );
		}

		if( isset( $_POST['schdule_dj-end-'.$key] ) ) {
			update_post_meta( $post_id,'schdule_dj-end-'.$key, esc_attr( $_POST['schdule_dj-end-'.$key] ) );
		}
	}
}
</pre>
<p>Once again, you see the usefulness of our global days variable. In this function, we loop through each day and we save our options from our select field by changing the name as the days loops through.</p>
<hr />
<h2><span>Step 3</span> Saving the Meta Boxes</h2>
<p>Wow! If you&#8217;re still with me, let&#8217;s put all these codes to work, shall we? Ok, great! The snippet below demonstrates how we&#8217;re going to loop through each schedule that we created and place in divs. Add that bit of code and let&#8217;s break it down.</p>
<pre name="code" class="php">
function show_schedule() {
	global $days;
	$html='';
	$html.= '&lt;div&gt;';
	$args = array( 'post_type' =&gt; 'dj_schedule');
	$loop = new WP_Query( $args );
	foreach ( $loop-&gt;posts as $item ):
		$html.= '&lt;div class="scheduleBox"&gt;';
		$html.= '&lt;h3&gt;'.$item-&gt;post_title.'&lt;/h3&gt;';
		$dj_id = get_post_meta($item-&gt;ID, 'dj_id', true);
		$dj = get_post($dj_id);
		$html.= '&lt;div&gt;'.$dj-&gt;post_title.'&lt;/div&gt;';
		$html.= '&lt;div&gt;'.get_the_post_thumbnail($dj-&gt;ID, 'dj-pic').'&lt;/div&gt;';
		foreach( $days as $key =&gt; $value ) {
			$start = get_post_meta($item-&gt;ID, 'schdule_dj-start-'.$key, true);
			$end = get_post_meta($item-&gt;ID, 'schdule_dj-end-'.$key, true);
			if ( $start &lt;&gt; 0 )
				$html.= '&lt;div id="time"&gt;'.$value.'   '.$start.'-'.$end.'&lt;/div&gt;';
		}
		$html.= '&lt;/div&gt;';
	endforeach;
	$html.= '&lt;div style="clear:both;"&gt;&lt;/div&gt;';
	$html.='&lt;/div&gt;';
	return $html;
}
</pre>
<p>Firstly, we make a loop for our custom post type <code>dj_schedule</code>, create a div and list the title. While inside the div, we fetch the DJ ID we added in the admin using the <code>get_post_meta</code> function. Then we use that same ID and call the WordPress function <code>get_post</code> for the values of that post and assign them to a variable which we then use to get the DJ&#8217;s name and photo.</p>
<h3>Getting the Time Slots</h3>
<p>Directly below our DJ, we have our day loop which loops through each day while making a check to see if any start time exists for that day. If they do exist, then we output the start and end time into a div.</p>
<h3>Adding Our Schedule to a Page</h3>
<p>We can do many things to add the schedule to a page, but for this tutorial, we will simply use a shortcode. So, with just one line of code, we will create a short code that we can call add on any page and voila! We have a working radio schedule!</p>
<pre name="code" class="php">add_shortcode('show_schedule', 'show_schedule');</pre>
<hr />
<h2>Conclusion</h2>
<p>This is the first phase of adding more great features to your WP radio website. I have chosen some simple styling for the layout, you can add these styles to your <strong>style.css</strong> file. In another tutorial, I will explain how to create a nice live stream pop-up with current show, DJ and radio player.</p>
<pre name="code" class="css">
.scheduleBox { background-color: #333333; border: #000000 1px solid; color: #fafafa; float: left; margin-left: 10px; height: 100%; }
.scheduleBox h3 { font-size: 14px; }
.scheduleBox #time { background: #666666; border-bottom: #000000 1px solid; }

.scheduleBox:hover { background-color: #000; border: #000000 1px solid; color: #FFCC00; float: left; margin-left: 10px; }
.scheduleBox h3:hover { color: #FF9900; }
.scheduleBox #time:hover { background: #333333; border-bottom: #000000 1px solid; }
</pre>
<hr />
<p>Your feedback is much appreciated. Let me know what you think in the comments below. Happy coding!</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/how-to-make-a-radio-station-schedule-using-wordpress/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Best of Tuts+ in May 2012</title>
		<link>http://wp.tutsplus.com/articles/news/best-of-tuts-in-may-2012/</link>
		<comments>http://wp.tutsplus.com/articles/news/best-of-tuts-in-may-2012/#comments</comments>
		<pubDate>Fri, 01 Jun 2012 09:37:28 +0000</pubDate>
		<dc:creator>David Appleyard</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[bestof]]></category>
		<category><![CDATA[monthlypicks]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25545</guid>
		<description><![CDATA[<p>Each month, we bring together a selection of the best tutorials and articles from across the whole <a href="http://tutsplus.com/">Tuts+ network</a>. Whether you&#8217;d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!</p>
<p><span id="more-25545"></span></p>
<hr />
<h2>Psdtuts+ — Photoshop Tutorials</h2>
<ul class="webroundup">
<li class='clear'>
<div>
		<img src="http://d2f8dzk2mhcqts.cloudfront.net/0685_Angel/preview.jpg" alt="Quick Tip: Create a Metallic Copper Text Effect Using Layer Styles in Photoshop" width="200" height="200" />
	</div>
<h4><a href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/metallic-copper-text-effect/'>Quick Tip: Create a Metallic Copper Text Effect Using Layer Styles in Photoshop</a></h4>
<p>In this tutorial we will explain how to create a metallic copper text effect using layer styles in Photoshop. Let&#8217;s get started!</p>
<p><a href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/metallic-copper-text-effect/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2f8dzk2mhcqts.cloudfront.net/0869_Camera/preview.jpg" alt="How to Draw a Leica Camera in Photoshop" width="200" height="200" />
	</div>
<h4><a href='http://psd.tutsplus.com/tutorials/drawing/draw-a-leica-camera/'>How to Draw a Leica Camera in Photoshop</a></h4>
<p>Leica is considered one of the most prestigious camera brands. In this tutorial, we will draw one of the most notable Leica cameras in Photoshop, the Leica M1. Let&#8217;s get started!</p>
<p><a href='http://psd.tutsplus.com/tutorials/drawing/draw-a-leica-camera/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2f8dzk2mhcqts.cloudfront.net/Premium_161_Sweets/preview.jpg" alt="Create a Tasty 3D Typographic Illustration &#8211; Tuts+ Premium Tutorial" width="200" height="200" />
	</div>
<h4><a href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/tasty-3d-typographic-illustration/'>Create a Tasty 3D Typographic Illustration &#8211; Tuts+ Premium Tutorial</a></h4>
<p>If you&#8217;ve got a sweet tooth, then we&#8217;ve got a mouth-watering tutorial for you. In this <a href="http://tutsplus.com/?WT.mc_id=premium_psdtuts_ed" >Tuts+ Premium</a> tutorial, author Mark Mayers will show you how Photoshop CS6 Extended&#8217;s new 3D tools can be utilized to create a typographic illustration that includes lots of sugary treats. This tutorial is available exclusively to Tuts+ Premium Members. </p>
<p><a href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/tasty-3d-typographic-illustration/'>Visit Article</a></p>
</li>
<hr />
<h2>Nettuts+ — Web Development Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://d2o0t5hpnwv4c1.cloudfront.net/2050_yui/preview.jpg" alt="10 Things I Learned While Interning at YUI" width="200" height="200" />
	</div>
<h4><a href='http://net.tutsplus.com/articles/general/10-things-i-learned-while-interning-at-yui/'>Things I Learned While Interning at YUI</a></h4>
<p>For eight months, I had the opportunity to intern with the YUI Team at Yahoo, while I was completing my engineering degree. Today, I&#8217;d like to share the top ten things that I learned from my experience with YUI.</p>
<p><a href='http://net.tutsplus.com/articles/general/10-things-i-learned-while-interning-at-yui/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2o0t5hpnwv4c1.cloudfront.net/058_CodaTechniques/200x200.png" alt="Coda 2: Reviewed" width="200" height="200" />
	</div>
<h4><a href='http://net.tutsplus.com/articles/reviews/coda-2-review/'>Coda 2: Reviewed</a></h4>
<p>Well, it happened; Panic <a href="http://panic.com/coda" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','panic.com']);">finally released</a> the long-awaited version two of their popular code editor, Coda. But does it live up to the hype? Well, that depends on what type of coder you are. Read the full review after the jump!</p>
<p><a href='http://net.tutsplus.com/articles/reviews/coda-2-review/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2o0t5hpnwv4c1.cloudfront.net/2047_softwarePrinciples/threeprinciples.png" alt="3 Key Software Principles You Must Understand" width="200" height="200" />
	</div>
<h4><a href='http://net.tutsplus.com/tutorials/tools-and-tips/3-key-software-principles-you-must-understand/'>Key Software Principles You Must Understand</a></h4>
<p>If you&#8217;re in software development, new techniques, languages and concepts pop up all of the time. We all feel those nagging doubts every now and then: &#8220;can I keep up with the changes and stay competitive?&#8221; Take a moment, and sum a line from my favourite movie, Casablanca: &#8220;The fundamental things apply, as time goes by.&#8221;</p>
<p><a href='http://net.tutsplus.com/tutorials/tools-and-tips/3-key-software-principles-you-must-understand/'>Visit Article</a></p>
</li>
<hr />
<h2>Vectortuts+ — Illustrator Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://dsmy2muqb7t4m.cloudfront.net/tuts/000-2012/514-victorian/preview.jpg" alt="Create a Vintage Vector Framed Silhouette Design" width="200" height="200" />
	</div>
<h4><a href='http://vector.tutsplus.com/tutorials/illustration/vintage-vector-silhouette/'>Create a Vintage Vector Framed Silhouette Design</a></h4>
<p>In today&#8217;s tutorial I&#8217;m going to collaborate with a great friend of mine, <a href="http://pixelledanddead.deviantart.com/" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','pixelledanddead.deviantart.com']);">Ashley Benson</a> and show you how to create a Victorian styled Silhouette. She&#8217;s been great to give me this wonderful sketch specifically for our vintage vector art tutorial, so feel free to download it as part of your Tuts+ Premium membership to practice on. Learn basic techniques on creating a detailed, framed silhouette inspired by Victorian vintage postcard designs using scatter brushes, patterns and more. Using these techniques you can create your own vintage illustrations.</p>
<p><a href='http://vector.tutsplus.com/tutorials/illustration/vintage-vector-silhouette/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://dsmy2muqb7t4m.cloudfront.net/qt/2012_QT/qt_54_corel_stock/Preview.jpg" alt="Quick Tip: Microstock Illustrations with Corel Draw, Tricks and Tips" width="200" height="200" />
	</div>
<h4><a href='http://vector.tutsplus.com/tutorials/tools-tips/quick-tip-microstock-illustrations-with-corel-draw-tricks-and-tips/'>Quick Tip: Microstock Illustrations with Corel Draw, Tricks and Tips</a></h4>
<p>With the vector software Corel Draw you are able to draw everything you can imagine. However, if you are using it to create illustrations for the microstock agencies &#8211; there are some issues that you must take into consideration. The problem comes with the industry requirement to provide an EPS (Encapsulated PostScript) file, which is mandatory for almost all agencies. See, EPS is Adobe standard and Corel developers don&#8217;t like Adobe standards very much&#8230;</p>
<p><a href='http://vector.tutsplus.com/tutorials/tools-tips/quick-tip-microstock-illustrations-with-corel-draw-tricks-and-tips/'>Visit Article</a></p>
</li>
<li class='clear'>
<div><img src="http://dsmy2muqb7t4m.cloudfront.net/articles/2010/news_2010_6_22/thumbnail.jpg" alt="From a Logo to Business Card, How to Make a Self Promotion Set" width="200" height="200" /></p></div>
<h4><a href='http://vector.tutsplus.com/sessions/logo-and-identity-design/'>Logo and Identity Design Session</a></h4>
<p>Audiences identify with effective logos and well composed brand identities. Learn how to craft creative logo designs with impact. In this Creative Session, we have a compilation of inspiring logo design and branding material.</p>
<p><a href='http://vector.tutsplus.com/sessions/logo-and-identity-design/'>Visit Article</a></p>
</li>
<hr />
<h2>Webdesigntuts+ — Web Design Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://d3pr5r64n04s3o.cloudfront.net/tuts/333_rounded_corners/preview.png" alt="Quick Tip: Rounded Corners Done Right" width="200" height="200" />
	</div>
<h4><a href='http://webdesign.tutsplus.com/tutorials/visuals/quick-tip-rounded-corners-done-right/'>Quick Tip: Rounded Corners Done Right</a></h4>
<p>This is going to seem like a no-brainer to many of you, but I see it happening so often I figured it was worth bringing up. We&#8217;ll call this issue <em>improperly nested corners</em>; a small detail which can ruin an otherwise brilliant design!</p>
<p><a href='http://webdesign.tutsplus.com/tutorials/visuals/quick-tip-rounded-corners-done-right/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d3pr5r64n04s3o.cloudfront.net/tuts/332_audio/tut/images/preview.png" alt="Create a Customized HTML5 Audio Player" width="200" height="200" />
	</div>
<h4><a href='http://webdesign.tutsplus.com/tutorials/site-elements/create-a-customised-html5-audio-player/'>Create a Customized HTML5 Audio Player</a></h4>
<p>During this tutorial I&#8217;m going to be introducing you to HTML5 audio and showing you how you can create your own player.</p>
<p><a href='http://webdesign.tutsplus.com/tutorials/site-elements/create-a-customised-html5-audio-player/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d3pr5r64n04s3o.cloudfront.net/tuts/329_aida/pree.png" alt="Employing AIDA Principles in Web Design" width="200" height="200" />
	</div>
<h4><a href='http://webdesign.tutsplus.com/articles/design-theory/employing-aida-principles-in-web-design/'>Employing AIDA Principles in Web Design</a></h4>
<p>In this article we&#8217;ll discuss how we can use design to implement the principles laid out by AIDA (the <a href="http://en.wikipedia.org/wiki/AIDA_(marketing)" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','en.wikipedia.org']);">marketing acronym</a>, not the <a href="http://en.wikipedia.org/wiki/Aida" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','en.wikipedia.org']);" rel="external">Italian opera</a>) and help create sales-orientated web pages.</p>
<p><a href='http://webdesign.tutsplus.com/articles/design-theory/employing-aida-principles-in-web-design/'>Visit Article</a></p>
</li>
<hr />
<h2>Phototuts+ — Photography Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://tutsplus.s3.amazonaws.com/tutspremium/photography/079_travel28mm/preview.jpg" alt="Simplify and Challenge Your Creativity Using a Single Lens &#8211; Tuts+ Premium" width="200" height="200" />
	</div>
<h4><a href='http://photo.tutsplus.com/tutorials/hardware-tutorials/simplify-and-challenge-your-creativity-using-a-single-lens-tuts-premium/'>Simplify and Challenge Your Creativity Using a Single Lens &#8211; Tuts+ Premium</a></h4>
<p>We have anotherÂ <a href="http://tutsplus.com/take-the-tour/" >Photo Premium</a> tutorial exclusively available to Premium members today. In this tutorial, try going out on a shoot with only one lens to limit us and force us to think creatively. Luckily, we&#8217;ll be guided by professional photographer Simon Plant. Learn more after the jump!<span id="more-9109"></span></p>
<p><a href='http://photo.tutsplus.com/tutorials/hardware-tutorials/simplify-and-challenge-your-creativity-using-a-single-lens-tuts-premium/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2f29brjr0xbt3.cloudfront.net/898_moonshooting/preview.jpg" alt="Easy Tips for Shooting the Moon" width="200" height="200" />
	</div>
<h4><a href='http://photo.tutsplus.com/articles/shooting-articles/easy-tips-for-shooting-the-moon/'>Easy Tips for Shooting the Moon</a></h4>
<p>Pictures of a big moon over a landscape are many times the result of a double exposure. Even when the moon comes closer to Earth, as it did recently, it is too small to fill the frame with normal gear. Still, there are ways to get around the thousands of miles that separate us and our big nightlight.<span id="more-9150"></span></p>
<p><a href='http://photo.tutsplus.com/articles/shooting-articles/easy-tips-for-shooting-the-moon/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2f29brjr0xbt3.cloudfront.net/909_visualnarratives/visualnarrative01_JA.jpg" alt="Building a Narrative Through Photojournalism" width="200" height="200" />
	</div>
<h4><a href='http://photo.tutsplus.com/articles/shooting-articles/building-a-narrative-through-photojournalism/'>Building a Narrative Through Photojournalism</a></h4>
<p>Telling visual stories is the work and craft of the photojournalist. I remember it from the first hard news story I covered, back in 1980: a bank robbery that completely defined my future.<span id="more-9212"></span> </p>
<p><a href='http://photo.tutsplus.com/articles/shooting-articles/building-a-narrative-through-photojournalism/'>Visit Article</a></p>
</li>
<hr />
<h2>Cgtuts+ — Computer Graphics Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://d2d04grx5ahzvh.cloudfront.net/385_Max_CAT797_Pt1/Thumb.jpg" alt="Building The Caterpillar 797 In 3D Studio Max &#8211; Creating The Tires, Rims, Cabin And Bridge" width="200" height="200" />
	</div>
<h4><a href='http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/building-the-caterpillar-797-in-3d-studio-max-creating-the-tires-rims-cabin-and-bridge/'>Building The Caterpillar 797 In 3D Studio Max &#8211; Creating The Tires, Rims, Cabin And Bridge</a></h4>
<p>Today we&#8217;re kicking off an awesome new tutorial series by Sasa Posloncec where you&#8217;ll learn how to model the ridiculously huge Caterpillar 797B mining dump truck. Spanning three parts this series will give you an in-depth look at what it takes to create a fully realized vehicle model in 3D Studio Max using blueprints and photo reference. As Sasa walks you through the creation of each part, you&#8217;ll learn how to work with Max&#8217;s Edit Poly modifier, spline tools and much more!<span id="more-15006"></span></p>
<p><a href='http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/building-the-caterpillar-797-in-3d-studio-max-creating-the-tires-rims-cabin-and-bridge/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2d04grx5ahzvh.cloudfront.net/392_Maya_IBL/Thumb.jpg" alt="Image Based Lighting: The Complete Workflow with Maya, HDR Shop &#038; Photoshop" width="200" height="200" />
	</div>
<h4><a href='http://cg.tutsplus.com/tutorials/autodesk-maya/image-based-lighting-the-complete-workflow-with-maya-hdr-shop-photoshop/'>Image Based Lighting: The Complete Workflow with Maya, HDR Shop &#038; Photoshop</a></h4>
<p>So Image Based Lighting&#8230;. What is it, and how can you use it to your advantage? Get the answers in this tutorial from James Whiffin where you&#8217;ll not only learn about implementing IBL into your projects, but how to setup and shoot your very own high dynamic range images, a topic rarely seen in tutorials.</p>
<p><a href='http://cg.tutsplus.com/tutorials/autodesk-maya/image-based-lighting-the-complete-workflow-with-maya-hdr-shop-photoshop/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d2d04grx5ahzvh.cloudfront.net/391_Blender_Interior_Modeling/Thumb.jpg" alt="Modeling A Modern Interior Scene In Blender" width="200" height="200" />
	</div>
<h4><a href='http://cg.tutsplus.com/tutorials/blender/modeling-a-modern-interior-scene-in-blender/'>Modeling A Modern Interior Scene In Blender</a></h4>
<p>In this tutorial we will be modeling an interior scene from a reference photo. It is written for the complete beginner, you&#8217;ll learn how to setup a background image and how to match the camera to it, as we follow a very simple workflow for building up the scene with a variety of basic modeling techniques that will give you a very good basis on how to approach any kind of modeling.</p>
<p><a href='http://cg.tutsplus.com/tutorials/blender/modeling-a-modern-interior-scene-in-blender/'>Visit Article</a></p>
</li>
<hr />
<h2>Aetuts+ — After Effects Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://tutsplus.s3.amazonaws.com/tutspremium/after-effects/71_face_capture/Facial_Capture_Thumb.png" alt="Fantastic Facial Motion Capture &#8211; Tuts+ Premium" width="200" height="200" />
	</div>
<h4><a href='http://ae.tutsplus.com/tutorials/vfx/fantastic-facial-motion-capture-tuts-premium/'>Fantastic Facial Motion Capture &#8211; Tuts+ Premium</a></h4>
<p>In this tutorial, I will be sharing with you how to achieve 2D facial motion capture in After Effects. The technique involves acquiring motion data from dots on a face, and using that motion data to manipulate the position of puppet pins on an image that you want to animate. It&#8217;s a very useful way of quickly creating detailed animations, and characterizing inanimate objects, like the rock face in the intro. It&#8217;s also possible to do face replacement.</p>
<p><a href='http://ae.tutsplus.com/tutorials/vfx/fantastic-facial-motion-capture-tuts-premium/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d3gphd0pfuxn95.cloudfront.net/736_burn/200px.jpg" alt="Muted Color Grading And A Vintage Film Burn Using Fractal Noise" width="200" height="200" />
	</div>
<h4><a href='http://ae.tutsplus.com/tutorials/vfx/muted-color-grading-and-a-vintage-film-burn-using-fractal-noise/'>Muted Color Grading And A Vintage Film Burn Using Fractal Noise</a></h4>
<p>In today&#8217;s tutorial I&#8217;ll be showing how to take DSLR footage and give it the popular &#8220;Muted&#8221; color grade.  After we cover the color grading, I&#8217;m gonna show you how to create a film burn effect from scratch using &#8220;Fractal Noise.&#8221;</p>
<p><a href='http://ae.tutsplus.com/tutorials/vfx/muted-color-grading-and-a-vintage-film-burn-using-fractal-noise/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d3gphd0pfuxn95.cloudfront.net/746_jumper/punch_thumb.jpg" alt="How To Create A Stupendous Stuttering Jumper Punch" width="200" height="200" />
	</div>
<h4><a href='http://ae.tutsplus.com/tutorials/vfx/how-to-create-a-stupendous-stuttering-jumper-punch/'>How To Create A Stupendous Stuttering Jumper Punch</a></h4>
<p>In this tutorial we will learn how to create an advanced and well composited <strong>Jumper Punch</strong> by using a matte, some displacement, and smoke to add style to the final effect. Throughout the tutorial, we will be using basic expressions. We&#8217;ll learn to position the jumps in time and space and give the illusion of a jumper disappearing and reappearing with a trajectory. Let&#8217;s &#8220;Jump&#8221; in&#8230; :)</p>
<p><a href='http://ae.tutsplus.com/tutorials/vfx/how-to-create-a-stupendous-stuttering-jumper-punch/'>Visit Article</a></p>
</li>
<hr />
<h2>Audiotuts+ — Audio &#038; Production Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://d3vvl31cy8gagb.cloudfront.net/528_3drouting/preview.jpg" alt="3D Mixing Part 7: Mastering, The Final Chapter (Part 2)" width="200" height="200" />
	</div>
<h4><a href='http://audio.tutsplus.com/tutorials/mixing-mastering/3d-mixing-part-7-mastering-the-final-chapter-part-2/'>D Mixing Part 7: Mastering, The Final Chapter (Part 2)</a></h4>
<p>In the final installment of the series, we are going to look at the final effects on the signal chain (Master EQ, Master Reverb, Master Limiter), and discuss the various final print options.</p>
<p><a href='http://audio.tutsplus.com/tutorials/mixing-mastering/3d-mixing-part-7-mastering-the-final-chapter-part-2/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d3vvl31cy8gagb.cloudfront.net/qt_179_snare/preview.jpg" alt="Quick Tip: How to Make a Snare Roll Generator" width="200" height="200" />
	</div>
<h4><a href='http://audio.tutsplus.com/tutorials/production/quick-tip-how-to-make-a-snare-roll-generator/'>Quick Tip: How to Make a Snare Roll Generator</a></h4>
<p>Today I will show you my new gadget, and teach you how to make it. A snare roll is an important part of a song. It can be used in many situations: as a creative element of a song or introducing something important like a breakdown. My new toy will reduce the time it takes to create one.</p>
<p><a href='http://audio.tutsplus.com/tutorials/production/quick-tip-how-to-make-a-snare-roll-generator/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://d3vvl31cy8gagb.cloudfront.net/743_10cures/preview.jpg" alt="10 Cures For A Songwriting Slump" width="200" height="200" />
	</div>
<h4><a href='http://audio.tutsplus.com/articles/general/10-cures-for-a-songwriting-slump/'>Cures For A Songwriting Slump</a></h4>
<p>Sooner or later, even the most inspired and prolific songwriter will stumble into that dreadful and frightening abyss known as writer&#8217;s block.  To call it frightening is truly not an overstatement when one is attempting to land a writing deal, keep a publisher happy, or best-case scenario, keep the already lucrative royalties flowing. The voice of defeat stirs in every songwriter at some point, first as a murmur and then as a blood-curdling scream.</p>
<p><a href='http://audio.tutsplus.com/articles/general/10-cures-for-a-songwriting-slump/'>Visit Article</a></p>
</li>
<hr />
<h2>Wptuts+ — WordPress Tutorials</h2>
<li class='clear'>
<div>
		<img src="http://wptutsplus.s3.amazonaws.com/267_The_Complete_Guide_To_The_WordPress_Settings_API_Part_8_Validation_Sanitisation_and_Input_II/wp-api-8.png" alt="The Complete Guide To The WordPress Settings API, Part 8: Validation, Sanitisation, and Input II" width="200" height="200" />
	</div>
<h4><a href='http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-8-validation-sanitisation-and-input-ii/'>The Complete Guide To The WordPress Settings API, Part 8: Validation, Sanitisation, and Input II</a></h4>
<p>We&#8217;ve reached the final article of the series. <a href="http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-7-validation-sanitisation-and-input-i/" >In the last post</a>, we took a look at introducing validation, sanitization, and a couple of basic input elements that we can take advantage of when building option pages.</p>
<p><a href='http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-8-validation-sanitisation-and-input-ii/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://wptutsplus.s3.amazonaws.com/268_Quick_Tip_Conditionally_Including_JS_and_CSS_With_get_current_screen/preview.png" alt="Quick Tip: Conditionally Including JS and CSS With get_current_screen" width="200" height="200" />
	</div>
<h4><a href='http://wp.tutsplus.com/articles/tips-articles/quick-tip-conditionally-including-js-and-css-with-get_current_screen/'>Quick Tip: Conditionally Including JS and CSS With get_current_screen</a></h4>
<p>As <a href="http://wp.tutsplus.com/articles/tips-articles/quick-tip-conditional-javascript-and-css-enqueueing-on-front-end-pages/" >many stated</a> before me: &#8220;A good WordPress citizen only loads their files where they&#8217;re needed&#8221;. This principle applies both to front-end and back-end (admin). There&#8217;s no justification for loading CSS and JS files on every admin page when you only need them on one single page you created. Thankfully doing things the right way is only one function call away.<span id="more-25378"></span></p>
<p><a href='http://wp.tutsplus.com/articles/tips-articles/quick-tip-conditionally-including-js-and-css-with-get_current_screen/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="http://wptutsplus.s3.amazonaws.com/273_Adding_Post_Series_Functionality_to_WordPress_With_Taxonomies/thumb.jpg" alt="Adding Post Series Functionality to WordPress With Taxonomies" width="200" height="200" />
	</div>
<h4><a href='http://wp.tutsplus.com/tutorials/plugins/adding-post-series-functionality-to-wordpress-with-taxonomies/'>Adding Post Series Functionality to WordPress With Taxonomies</a></h4>
<p>Ever wrote a &#8220;post series&#8221; on your blog? If you did, you probably needed to add the links of the other parts of the series into the latest post you wrote. Each time you finished a new part, you had to update the link list of the other parts. There has to be an easier way, right?<span id="more-25414"></span></p>
<p><a href='http://wp.tutsplus.com/tutorials/plugins/adding-post-series-functionality-to-wordpress-with-taxonomies/'>Visit Article</a></p>
</li>
<hr />
<h2>Mobiletuts+ — Mobile Development Tutorials</h2>
<li class='clear'>
<div>
		<img src="https://d339vfjsz5zott.cloudfront.net/iOS-SDK_UIKit-Theme-Customization/preview.png" alt="iOS SDK: UIKit Theme Customization" width="200" height="200" />
	</div>
<h4><a href='http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-uikit-theme-customization/'>iOS SDK: UIKit Theme Customization</a></h4>
<p>Theme customization is a great way to stand out in the App Store, but it isn&#8217;t always easy to achieve. This tutorial will teach you several basic UIKit customization tricks that will help distinguish your applications and create more memorable user experiences.<br />
<span id="more-10777"></span></p>
<p><a href='http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-uikit-theme-customization/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="https://d339vfjsz5zott.cloudfront.net/Unity3D_Introduction/preview_image.png" alt="Introduction to Unity3D" width="200" height="200" />
	</div>
<h4><a href='http://mobile.tutsplus.com/tutorials/android/introduction-to-unity3d/'>Introduction to Unity3D</a></h4>
<p>Unity3D is a powerful cross-platform 3D engine and a user-friendly development environment. Learn how Unity3D can help you create games in this article!<br />
<span id="more-10752"></span></p>
<p><a href='http://mobile.tutsplus.com/tutorials/android/introduction-to-unity3d/'>Visit Article</a></p>
</li>
<li class='clear'>
<div>
		<img src="https://d339vfjsz5zott.cloudfront.net/Android-SDK_Wireshark_Traffic-Analysis/android-traffic.png" alt="Analyzing Android Network Traffic" width="200" height="200" />
	</div>
<h4><a href='http://mobile.tutsplus.com/tutorials/android/analyzing-android-network-traffic/'>Analyzing Android Network Traffic</a></h4>
<p>Network traffic analysis can be a vital part of the software debugging and testing process. This tutorial will teach you how to monitor all incoming and outgoing traffic on an Android device in order to better debug your applications!<br />
<span id="more-10663"></span></p>
<p><a href='http://mobile.tutsplus.com/tutorials/android/analyzing-android-network-traffic/'>Visit Article</a></p>
</li>
</ul>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/articles/news/best-of-tuts-in-may-2012/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fast BuddyPress Development</title>
		<link>http://wp.tutsplus.com/tutorials/plugins/fast-buddypress-development/</link>
		<comments>http://wp.tutsplus.com/tutorials/plugins/fast-buddypress-development/#comments</comments>
		<pubDate>Thu, 31 May 2012 10:35:17 +0000</pubDate>
		<dc:creator>Alistair Rossini</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[BuddyPress]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25396</guid>
		<description><![CDATA[<p>Working with BuddyPress on top of WordPress is a super exciting thing, it adds a whole new dimension to the platform and really demonstrates huge potential.</p>
<p>BuddyPress like other plugins expands on the core functionality WordPress offers. Although it is important as a freelancer or company to recognise that BuddyPress unlike other plugins adds functionality of epic proportions.</p>
<p>This tutorial aims to show you how to demonstrate a proof of concept quickly and functionally without making any best practice cardinal sins.<span id="more-25396"></span></p>
<hr />
<h2>Introduction</h2>
<p>Over the course of this tutorial we will use a combination of PHP, jQuery and WordPress functions to extend BuddyPress far enough to demonstrate a concept.</p>
<p>Working on member profiles we will without any recourse add a link that allows users to visit a member bookmarks area.</p>
<p>The bookmarks area will be populated with a list of bookmarks a member has decided to save whilst browsing any BuddyPress enabled site.</p>
<p>The scope of bookmarks which can be saved will only be applied to WordPress posts for now, however you may look to build on this further and apply it to other areas of a WordPress powered web site that produces a permalink.</p>
<hr />
<h2 id="step1"><span>Step 1</span> The Essentials</h2>
<p>We will be building upon the <strong>bp-default</strong> theme today and creating our own child theme. Below is the structure you should have created.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/270_Fast_BuddyPress_Development_Without_Commiting_Cardinal_Sin/img1.png" alt="Theme structure" /></div>
<ul>
<li><strong>style.css</strong> &ndash; Some additional styles for icons, buttons and lists (this will not be discussed).</li>
<li><strong>sidebar.php</strong> &ndash; We will call our widget from here.</li>
<li><strong>header.php</strong> &ndash; One modification required.</li>
<li><strong>functions.php</strong> &ndash; Register scripts and a apply a filter.</li>
<li><strong>_inc/img/</strong> &ndash; A number of image files to be used.</li>
<li><strong>_inc/js/bookmarks.js</strong> &ndash; jQuery and AJAX.</li>
<li><strong>members/single/home.php</strong> &ndash; Some PHP logic to enable the template loader.</li>
<li><strong>members/single/bookmarks/ajax.php</strong> &ndash; Used for our AJAX calls.</li>
<li><strong>members/single/bookmarks/loop.php</strong> &ndash; Retrieval of bookmarks via member profiles.</li>
<li><strong>members/single/bookmarks/remove.php</strong> &ndash; Deletion of bookmarks via my member profile.</li>
<li><strong>members/single/bookmarks/save.php</strong> &ndash; Storage of bookmarks via my member profile.</li>
<li><strong>members/single/bookmarks/view.php</strong> &ndash; Hacky bookmark template loader.</li>
<li><strong>members/single/bookmarks/widget.php</strong> &ndash; Called into site <strong>sidebar.php</strong>.</li>
</ul>
<p><strong>style.css</strong> &ndash; Within <strong>style.css</strong> we need a bare minimum amount of code to allow for theme selection via <strong>wp-admin</strong>. Let&#8217;s do that now.</p>
<pre name="code" class="css">
/*
Theme Name: Bookmark theme
Description: Child theme from bp-default with added support for member bookmarks.
Version: 1.0
Author: WPTuts
Author URI: http://wp.tutsplus.org
Tags: buddypress
Template: bp-default
*/
</pre>
<p><code>Tags: buddypress</code> will notify BuddyPress that we are using a BP enabled theme.</p>
<p><code>Template: bp-default</code> will instruct BuddyPress that when this theme is active to inherit its functionality from the <strong>bp-default</strong> theme unless a theme file has been modified.</p>
<p>Within <strong>sidebar.php</strong> we need to load the <strong>widget.php</strong>.</p>
<pre name="code" class="php">
locate_template(array('members/single/bookmarks/widget.php'), true);
</pre>
<hr />
<h2 id="step2"><span>Step 2</span> functions.php &ndash; Register Script</h2>
<p>Let&#8217;s go ahead and register the <strong>bookmarks.js</strong> file, it will be required on every page from here on out. In <strong>functions.php</strong> add the following.</p>
<pre name="code" class="php">
function px_bookmark_scripts() {
	if(!is_admin()) {
		wp_enqueue_script(
			'px-scripts-functions',
			get_stylesheet_directory_uri() . '/_inc/js/bookmarks.js',
			array('jquery'),
			'1.0',
			true
		);
	}
}
add_action('wp_enqueue_scripts','px_bookmark_scripts');
</pre>
<p><code><a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">wp_enqueue_script</a></code> accepts 5 parameters.</p>
<ol>
<li>Handle &ndash; Give your script a name.</li>
<li>Source &ndash; Path to your script.</li>
<li>Dependencies &ndash; Which scripts will your script need to function.</li>
<li>Version &ndash; Version number of your script.</li>
<li>In footer &ndash; If false your script will be loaded with <code>wp_head</code>. If set to true it will load with <code>wp_footer</code>.</li>
</ol>
<hr />
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/270_Fast_BuddyPress_Development_Without_Commiting_Cardinal_Sin/img2.png" alt="Anchor attached to post" /></div>
<p>Browsers of our site will be able to add or remove a WordPress post to their bookmarks by clicking an anchor which reads &#8220;Add to bookmarks&#8221; or &#8220;Remove from bookmarks&#8221; located to the bottom of each post.</p>
<p>When either anchor is clicked we will use AJAX and make a request to a PHP script. Once executed we will update the sidebar widget.</p>
<p>Should the browser be logged in as a member of the site they can then save any &#8220;Lists of bookmarks&#8221; which are currently stored within the session and displayed in the widget.</p>
<p><strong>functions.php</strong>&#8230;</p>
<pre name="code" class="php">
function px_bookmark_link() {
	global $post;
	if(@in_array($post-&gt;ID, $_SESSION['bookmarks'])) :
		$content .= '&lt;a href="'.get_permalink().'" class="delete-bookmark" data-post-id="'.$post-&gt;ID.'" data-post-name="'.get_the_title().'"&gt;Remove from bookmarks&lt;/a&gt;';
	else :
		$content .= '&lt;a href="'.get_permalink().'" class="add-bookmark" data-post-id="'.$post-&gt;ID.'" data-post-name="'.get_the_title().'"&gt;Add to bookmarks&lt;/a&gt;';
	endif;
	return $content;
}
add_filter('the_tags', 'px_bookmark_link');
</pre>
<p>This function is called at each iteration of &#8220;the loop&#8221; by utilising <a href="http://codex.wordpress.org/Function_Reference/add_filter"><code>add_filter</code></a> and <a href="http://codex.wordpress.org/Plugin_API/Filter_Reference/the_tags"><code>the_tags</code></a> as our hook.</p>
<p>We let WordPress know that within this function we want access to items within <a href="http://codex.wordpress.org/Class_Reference/WP_Query"><code>$wp_query</code></a> and consequently <code>$post</code>. This will allow us to retrieve <code>the_id</code>, <code>the_title</code> and <code>the_permalink</code>.</p>
<p>Some logic is applied when this code executes to determine which link to show. If the user already has the item within their current session we will show a &#8220;Remove from bookmarks&#8221; anchor and vice versa. <a href="http://php.net/manual/en/function.in-array.php"><code>in_array()</code></a> allows us to check this.</p>
<p><code>in_array()</code> will flag notices if <code>error_reporting</code> has that directive, we use the <code>@</code> symbol to suppress these notices (hacky).</p>
<p>Using the data returned in <code>$post</code> we form two anchors for adding and removing bookmarks (all <a href="http://api.jquery.com/jQuery.data/"><code>data</code></a> attributes important here) to be later used with our AJAX calls in <strong>bookmarks.js</strong>.</p>
<p><em>For a full reference of available filters <a href="http://codex.wordpress.org/Plugin_API/Filter_Reference">visit the codex</a>.</em></p>
<hr />
<h2 id="step3"><span>Step 3</span> Widget &ndash; Proof of Concept</h2>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/270_Fast_BuddyPress_Development_Without_Commiting_Cardinal_Sin/img3.png" alt="Widget states" /></div>
<p>Now we have our link in place let&#8217;s create the widget which will appear in the sidebar at all times and will be populated or emptied on demand.</p>
<p>The image above reflects the final states of the widget in 3 scenarios.</p>
<ol>
<li>No bookmarks whilst being logged in or logged out.</li>
<li>Bookmarks currently saved in session <em>whilst not logged in</em>.</li>
<li>Bookmarks currently saved in session <em>whilst being logged in</em>.</li>
</ol>
<p>The next block of code is placed within <strong>widget.php</strong> and nested within HTML markup.</p>
<pre name="code" class="php">
if($_SESSION['bookmarks']) :
	foreach($_SESSION['bookmarks'] as $key =&gt; $value) :
		$keys[] = $key;
		$start_count = min($keys);
	endforeach;
endif;
for($i = $start_count; $i &lt; $start_count + count($_SESSION['bookmarks']); $i++) :
	if($_SESSION['bookmarks'][$i]) :
		$bookmark = get_post($_SESSION['bookmarks'][$i]);
		echo '&lt;li id="bookmark-'.$bookmark-&gt;ID.'"&gt;';
		echo '&lt;a href="'.$bookmark-&gt;post_name.'"&gt;'.$bookmark-&gt;post_title.'&lt;/a&gt;';
		echo '&lt;/li&gt;';
	endif;
endfor;
</pre>
<p>When building this project there was a problem with session data that kept cropping up upon output. Some values were being removed but the key was persisting. Setting a <code>$start_count</code> later to be used when printing the session data solved this problem.</p>
<p>The important thing to note here is how to retrieve items from <code>$_SESSION['bookmarks']</code> which will be created in the next stage.</p>
<p>At each iteration we use <a href="http://codex.wordpress.org/Function_Reference/get_post"><code>get_post()</code></a> to query the WordPress database with the stored integer values in <code>$_SESSION['bookmarks']</code>. Which will return all the human readable data we need.</p>
<pre name="code" class="php">
if(is_user_logged_in()) :
	// Show SAVE button
else :
	// Show "LOGIN TO SAVE" message.
endif;
if($_SESSION['bookmarks']) :
	// Show CLEAR button
endif;
</pre>
<p>This final piece of logic within <strong>widget.php</strong> determines which buttons and text to show alongside the widget depending on the state of the current session and<br />
also if the user is logged in or out.</p>
<hr />
<h2><span id="step4">Step 4</span> Adding Bookmarks via AJAX</h2>
<p>jQuery is awesome, here we&#8217;ll use the <a href="http://api.jquery.com/delegate/"><code>delegate</code></a> method and listen for clicks on our important anchors. We&#8217;ll check for the following items being clicked.</p>
<ul>
<li>Anchors with a class of <code>add-bookmark</code></li>
<li>Anchors with a class of <code>delete-bookmark</code></li>
<li>Anchors with a class of <code>clear-bookmarks</code></li>
</ul>
<p>Using <a href="http://api.jquery.com/hasClass/"><code>hasClass</code></a> we can test which item has been clicked within the delegate method and serve the desired <a href="http://api.jquery.com/jQuery.ajax/"><code>AJAX</code></a> call.</p>
<p>Should you be building this into a larger project please consider using a <em><a href="http://net.tutsplus.com/tutorials/javascript-ajax/loose-coupling-with-the-pubsub-plugin/">pubsub</a></em> pattern.</p>
<pre name="code" class="js">
var $bookmark_widget = $('#px-bookmarks'),
	$bookmark_form = $('#px-bookmarks form'),
	$bookmark_widget_list = $('#px-bookmarks .current-bookmarks'),
	$empty_widget = $('#px-bookmarks p'),
	$widget_buttons = $('#px-bookmarks .widget-buttons'),
	$login_notify = $('#px-bookmarks .login-notify'),
	// This should be changed to reflect your domain.
	$ajax_path = 'http://yoursite.com/wp-content/themes/bookmark-theme/members/single/bookmarks/ajax.php';
</pre>
<p>First log some variables so we are not &#8220;splashing around in the DOM&#8221; too much. All DOM selectors above are located within <strong>widget.php</strong>.</p>
<pre name="code" class="js">
$(".add-bookmark, .delete-bookmark, .clear-bookmarks").delegate(this, 'click', function(e) {
	e.preventDefault();
});
</pre>
<p>We tell jQuery to listen for click on all of the listed classes and via the callback function we will then tell it what to do. The next portions of code to be added will be placed directly after <code>e.preventDefault()</code>.</p>
<p>Using <a href="http://api.jquery.com/event.preventDefault/"><code>preventDefault()</code></a> is a smarter way of nullifying the default action when JavaScript is present. Here is some discussion surrounding <code>preventDefault()</code> on <a href="http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false">Stack Overflow</a>.</p>
<p>The next portions of code to be added will be placed directly after <code>e.preventDefault()</code>.</p>
<pre name="code" class="js">
var $post_id   = $(this).data('post-id'),
	$post_name = $(this).data('post-name'),
	$post_href = $(this).attr('href'),
	$that 	   = $(this);
</pre>
<p>Once a user has clicked any of the &#8220;important anchors&#8221; we need to store the data attribute values which were attached to anchors in <a href="#step2">Step 2</a>. This will allow us to send and retrieve the data we want.</p>
<p>The next code can become a little verbose as we will be showing and hiding elements based on which item has been clicked, with that pre-cursor the code below is the<br />
bare minimum which will function without aesthetics in mind. However please do download the source and look to these lines.</p>
<pre name="code" class="js">
if($that.hasClass('add-bookmark')) {
	$.ajax({
		url: $ajax_path + '?method=add',
		type: 'GET',
		data: 'post_id=' + $post_id,
		success: function(returndata) {
			if($bookmark_widget_list.children().length === 0) {
				// Show / hide
			}
			$bookmark_widget_list.prepend('&lt;li id="bookmark-'+ $post_id +'"&gt;
				&lt;a href="'+ $post_href +'"&gt;' + $post_name + '&lt;/a&gt;&lt;/li&gt;');
		}
	});
}
</pre>
<p>Here we use <code>hasClass</code> to distinguish which item was clicked by using jQuery to search against our clicked item.</p>
<p>Based on the outcome we setup our <a href="http://api.jquery.com/jQuery.ajax/"><code>AJAX</code></a> call a little bit differently each time. With the <code>url</code> and <code>data</code> being requested and sent each time changing slightly.</p>
<p>Notice <code>?method=add</code> appended to <code>$ajax_path</code>. This is the equivalent of <code>http://site.com/path/to/ajax.php?method=add</code>.</p>
<p>When adding a bookmark to the current session the only item we need to pass to our PHP code is the id of that post which was stored into the <code>$post_id</code> variable.</p>
<p>When jQuery receives a successful response we then append that item to the current bookmark list within the widget area as a list item. Using <code>$post_id</code>, <code>$post_name</code> and <code>$post_href</code> here.</p>
<p>When the page is refreshed the code added to <strong>widget.php</strong> in <a href="#step3">step 3</a> will kick in.</p>
<p>On line 7 of the last snippet there is a small subroutine within the <code>success</code> method which determines if there are any list items present within the widget area. This is the previously-mentioned-slightly-verbose code which does nothing more than show and hide some DOM elements. It has been removed for readability here on Wptuts+. Moving on&#8230;</p>
<pre name="code" class="js">
if($that.hasClass('delete-bookmark')) {
	$.ajax({
		url: $ajax_path + '?method=delete',
		type: 'GET',
		data: 'post_id=' + $post_id,
		success: function(returndata) {
			if($bookmark_widget_list.children().length <= 1) {
				// Show / hide
			}
			$('#bookmark-'+ $post_id).remove();
		}
	});
}
</pre>
<p>Much like <code>if($that.hasClass('add-bookmark'))</code> here we check for items clicked that have the class of <code>delete-bookmark</code>.</p>
<p>Once this subroutine has been entered the <code>url</code> in the AJAX call is altered slightly by sending over a different query string. Namely <code>?method=delete</code>.</p>
<p>When a successful response is returned we remove that list item from the current bookmarks stored within the widget.</p>
<p>Applying some logic in the same fashion as the <code>add-bookmark</code> subroutine to determine if the item removed is going to be the final item. Based on this outcome here DOM elements are again shown or hidden.</p>
<pre name="code" class="js">
if($that.hasClass('clear-bookmarks')) {
	$.ajax({
		url: $ajax_path + '?method=clear',
		success: function(returndata) {
			// Show / hide

			$('.postmetadata .delete-bookmark').each(function(index) {
				// Bookmark list cleared, set anchors attached to posts to default.
				$(this).removeClass().addClass('add-bookmark').html('Add to bookmarks');
			});
		}
	});
}
</pre>
<p>The final code snippet here is used to clear all bookmarks within the widget by setting the <code>url</code> query string to a different method and resetting any anchors on the page to the default "Add to bookmarks" to reflect an empty <code>$_SESSION</code>. This is done by utilising jQuery's <a href="http://api.jquery.com/each/"><code>each method</code></a> to find all occurrences of the class <code>delete-bookmark</code> (anchor attached to posts using <code>add_filter</code>) and switching it back to the default<br />
<code>add-bookmark</code>.</p>
<hr />
<h2><span id="step5">Step 5</span> PHP Requested via AJAX</h2>
<p>Now we will create the PHP code referenced in the AJAX calls above which will be used to add, delete and clear all bookmarks from the session.</p>
<p>Within <strong>ajax.php</strong> we will create the following 3 functions.</p>
<ul>
<li><code>add_bookmark()</code></li>
<li><code>delete_bookmark()</code></li>
<li><code>clear_bookmarks()</code></li>
</ul>
<p>Let's first create <code>add_bookmark()</code></p>
<pre name="code" class="php">
function add_bookmark() {
	$post_id = $_GET['post_id'];
	if(@!in_array($post_id, $_SESSION['bookmarks'])) :
		$_SESSION['bookmarks'][] = $post_id;
	endif;
}
</pre>
<p>First we store the <code>$post_id</code> previously passed over in <strong>bookmarks.js</strong> via <code>data: 'post_id=' + $post_id</code>.</p>
<p>Next we use the <code>in_array</code> function again to determine if this item should be added to the bookmarks session.</p>
<pre name="code" class="php">
function delete_bookmark() {
	$post_id = $_GET['post_id'];

	foreach($_SESSION['bookmarks'] as $key =&gt; $value) :
		$keys[] = $key;
	endforeach;
	$start_count = min($keys);

	if(@in_array($post_id, $_SESSION['bookmarks'])) :
		for($i = $start_count; $i &lt; $start_count + count($_SESSION['bookmarks']); $i++) :
			if($_SESSION['bookmarks'][$i] === $post_id) :
				unset($_SESSION['bookmarks'][$i]);
			endif;
		endfor;
	endif;
}
</pre>
<p>Within the <code>delete_bookmark()</code> function we again store the <code>$post_id</code>.</p>
<p>Using the same technique to output our bookmarks in <strong>widget.php</strong> a <code>$start_count</code> is established.</p>
<p>Next we determine if the item passed (<code>$post_id</code>) exists within the bookmarks session via <code>in_array</code>, and unset any values that are matched.</p>
<pre name="code" class="php">
function clear_bookmark() {
	session_start();
	session_unset();
	session_destroy();
}
</pre>
<p>Finally the <code>clear_bookmark()</code> function destroys all session data.</p>
<p>We will need one more piece of code for this file to be complete. Head to the top of the file and add the following.</p>
<pre name="code" class="php">
session_start();

$method = $_GET['method'];

switch($method) {
	case "add" :
		add_bookmark();
	break;
	case "delete" :
		delete_bookmark();
	break;
	case "clear" :
		clear_bookmark();
	break;
}
</pre>
<p>We use <code>session_start()</code> to resume the current session. This is crucial here.</p>
<p>Next we store the method which is sent over with <code>url</code> in our <code>$.ajax</code> calls.</p>
<p>Based on the current value of <code>$method</code> we call the appropriate function.</p>
<hr />
<h2><span id="step6">Step 6</span> Bookmarks on Members Profiles</h2>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/270_Fast_BuddyPress_Development_Without_Commiting_Cardinal_Sin/img4.png" alt="Member bookmarks" /></div>
<p>The files we will be dealing with for the remainder of this tutorial are listed below.</p>
<ul>
<li><strong>members/single/home.php</strong> &ndash; This file is a modified version of <strong>bp-default/members/single/home.php</strong>.</li>
<li><strong>members/single/bookmarks/loop.php</strong> &ndash; Used to retrieve any previously saved member bookmark lists.</li>
<li><strong>members/single/bookmarks/remove.php</strong> &ndash; Used to delete any saved bookmark lists.</li>
<li><strong>members/single/bookmarks/save.php</strong> &ndash; Used to save any bookmark lists stored within the current session.</li>
<li><strong>members/single/bookmarks/view.php</strong> &ndash; Used as a makeshift template loader.</li>
</ul>
<p>Inside <strong>home.php</strong> we will add a list item to the unordered list within the div with an id of <code>item-nav</code>.</p>
<p>Using the <a href="http://codex.buddypress.org/developer-docs/the-bp-global/"><code>$bp</code> global</a> we can quickly form the URL required.</p>
<pre name="code" class="php">
global $bp;
echo '&lt;li&gt;&lt;a href="'.$bp-&gt;displayed_user-&gt;domain.'?component=bookmarks"&gt;Bookmarks&lt;/a&gt;&lt;/li&gt;';
</pre>
<p>This is one of smaller sins we make along the road to demonstrate proof of concept. However to re-iterate proof-of-concept and speedy development is the important factor here.</p>
<p>Should we decide to expand this feature more we would look to using BuddyPress hooks.</p>
<pre name="code" class="php">
if($_GET['component'] == 'bookmarks') :
	locate_template(array('members/single/bookmarks/view.php'), true);
</pre>
<p>Still within <strong>home.php</strong> we check against the query string which will allow us to serve custom templates.</p>
<pre name="code" class="php">
if(!$_GET['action']) :
	locate_template(array( 'members/single/bookmarks/loop.php'), true);
elseif($_GET['action'] == 'save' &#038;&#038; is_user_logged_in() &#038;&#038; bp_is_home()) :
	locate_template(array( 'members/single/bookmarks/save.php'), true);
elseif($_GET['action'] == 'remove' &#038;&#038; is_user_logged_in() &#038;&#038; bp_is_home()) :
	locate_template(array( 'members/single/bookmarks/remove.php'  ), true);
endif;
</pre>
<p>Within <strong>view.php</strong> (our make-shift template loader) we check for 2 actions and if none has been defined we show the list of saved bookmarks.</p>
<p>Back in <a href="#step3">step 3</a> some logic was added to determine which anchors to show within the widget based on the current state of <code>$_SESSION['bookmarks']</code> and whether or not the user was logged in.</p>
<p>Let's create a small table in the database which will be used to store a list of bookmarks which correspond to each member.</p>
<pre name="code" class="php">
DROP TABLE IF EXISTS `bookmarks`;
CREATE TABLE `bookmarks` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`user_id` int(11) NOT NULL,
	`created` date NOT NULL,
	`post_ids` text NOT NULL,
	`list_name` text NOT NULL,
	PRIMARY KEY (`id`)
)
</pre>
<p>The MySQL above will create a new table with 5 fields for us to store bookmark data.</p>
<p>Once created it's time to move into <strong>save.php</strong>.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/270_Fast_BuddyPress_Development_Without_Commiting_Cardinal_Sin/img5.png" alt="Save list" /></div>
<p>Whilst the user is accessing <strong>save.php</strong> we will present a form with a text input, here the user will be required to give a label to the list of bookmarks he or she would like to save.</p>
<p>Once a label has been provided we will store each bookmark list as a row within the database (for later retrieval) and clear the current session.</p>
<pre name="code" class="php">
if(!$_POST['px-bookmark-list-name']) :
	// Present form asking to give list a name
	// Stage 1
elseif($_POST['px-bookmark-list-name']) :
	// Label supplied store to database.
	// Stage 2
endif;
</pre>
<p>Now within stage 1 of <strong>save.php</strong>...</p>
<pre name="code" class="php">
// If form submitted but no label supplied present error.
if($_POST['submit'] &#038;&#038; !isset($_POST['px-bookmark-list-name'])) :
	echo '&lt;p class="error"&gt;A label is required.&lt;/p&gt;';
endif;

// Establish the start counter
if($_SESSION['bookmarks']) :
	foreach($_SESSION['bookmarks'] as $key =&gt; $value) :
		$keys[] = $key;
	endforeach;
	$start_count = min($keys);
endif;

// Loop over items and store in hidden form fields.
for($i = $start_count; $i &lt; $start_count + count($_SESSION['bookmarks']); $i++) :
	if($_SESSION['bookmarks'][$i] !== NULL) :
		$bookmark = get_post($_SESSION['bookmarks'][$i]);
		echo '&lt;input type="hidden" name="px-post-url[]" value="'.$bookmark-&gt;post_name.'" /&gt;';
		echo '&lt;input type="hidden" name="px-post-name[]" value="'.$bookmark-&gt;post_title.'" /&gt;';
		echo '&lt;input type="hidden" name="px-post-id[]" value="'.$bookmark-&gt;ID.'" /&gt;';
		echo '&lt;input type="submit" name="submit" value="Save List"&gt;';
	endif;
endfor;
</pre>
<p>First we display an error if no label has been supplied.</p>
<p>Next we use the same technique from <strong>widget.php</strong> and <strong>ajax.php</strong> to establish a start counter and iterate over the session data.</p>
<p>Finally we output some form fields with the help of <code>get_post</code>.</p>
<pre name="code" class="php">
global $bp;

foreach($_POST['px-post-id'] as $value) :
	$posts_to_save[] = $value;
endforeach;

$posts = serialize($posts_to_save);
</pre>
<p>During stage 2 of <strong>save.php</strong> we gain access to the <code>$bp</code> global.</p>
<p>We loop over the <code>$_POST</code> data and store posts to be saved as an array. This is then serialized and stored into the <code>$posts</code> variable.</p>
<pre name="code" class="php">
$list_name = $_POST['px-bookmark-list-name'];

$query = $wpdb-&gt;insert(
	'bookmarks',
	array(
		'user_id'		=&gt; $bp-&gt;loggedin_user-&gt;id,
		'created'		=&gt; current_time('mysql'),
		'post_ids'		=&gt; $posts,
		'list_name'		=&gt; $list_name
	),
	array(
		'%d',			// user_id
		'%s',			// created
		'%s',			// post_ids
		'%s'			// list_name
	)
);
</pre>
<p>Next we store the label supplied by the user for this bookmark list into a variable and utilise <code>WPDB</code> to insert the row to the database.</p>
<pre name="code" class="php">
if($query) :
	echo '&lt;div id="message" class="updated"&gt;';
	echo '&lt;p&gt;List saved.&lt;/p&gt;';
	echo '&lt;/div&gt;';

	session_start();
	session_unset();
	session_destroy();
else :
	echo '&lt;div id="message" class="error"&gt;';
	echo '&lt;p&gt;There was an error.&lt;/p&gt;';
	echo '&lt;/div&gt;';
endif;
</pre>
<p>Finally we check if the query was successful and unset session data, otherwise display an error.</p>
<hr />
<h2><span id="step7">Step 7</span> Retrieving and Deleting Bookmarks</h2>
<p>Remember, in <strong>view.php</strong> when no particular <code>action</code> is set we will load <strong>loop.php</strong>. In this file <code>$wpdb</code> will be used to retrieve and output any bookmarks lists.</p>
<pre name="code" class="php">
global $bp;
$displayed_user = $bp-&gt;displayed_user-&gt;id;
$bookmark_lists = $wpdb-&gt;get_results( "SELECT * FROM bookmarks WHERE user_id = $displayed_user ORDER BY id DESC");
</pre>
<p>Using the <code>$bp</code> global the id of the profile being displayed is stored into the <code>$displayed_user</code> variable.</p>
<p>Next we perform a query against the bookmarks table with the stored <code>$displayed_user</code> as a where condition.</p>
<pre name="code" class="php">
if($bookmark_lists) :
	foreach($bookmark_lists as $bookmark_list) :
		echo $bookmark_list-&gt;list_name;
		$post_ids = unserialize($bookmark_list-&gt;post_ids);
		foreach($post_ids as $post_id) :
			$bookmark = get_post($post_id);
			echo '&lt;a href="http://yoursite.com/'.$bookmark-&gt;post_name.'" title="View bookmark"&gt;'.$bookmark-&gt;post_title.'&lt;/a&gt;';
		endforeach;
	endforeach;
endif;
</pre>
<p>When results are returned they are displayed by looping over the data and outputting accordingly. Here we make use of <code>unserialize</code> to reverse the effects of<br />
<code>serialize</code> which was used to store bookmarks previously.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/270_Fast_BuddyPress_Development_Without_Commiting_Cardinal_Sin/img6.png" alt="Remove bookmarks" /></div>
<p>We can make one more addition to the previous block of code.</p>
<pre name="code" class="php">
if(is_user_logged_in() &#038;&#038; bp_is_home()) :
	echo '&lt;a href="'.$bp-&gt;displayed_user-&gt;domain.'?component=bookmarks&#038;action=remove&#038;id='.$bookmark_list-&gt;id.'" class="delete-list"&gt;Delete list&lt;/a&gt;';
endif;
</pre>
<p>This will add an anchor to the title of each list which when clicked will pass a new action of <code>remove</code> along with the bookmark list id.</p>
<p>Which leads us to our final stage... Deleting a bookmark list. Open up <strong>remove.php</strong> and let's finish this off.</p>
<pre name="code" class="php">
if(isset($_GET['action']) == 'remove' &#038;&#038; isset($_GET['id'])) :
	$list_id = $_GET['id'];
	global $bp;
	$user_id = $bp-&gt;loggedin_user-&gt;id;
	$query = $wpdb-&gt;query("DELETE FROM bookmarks WHERE id = $list_id AND user_id = $user_id");

	if($query) :
		echo '&lt;div id="message" class="updated"&gt;';
		echo '&lt;p&gt;List deleted.&lt;/p&gt;';
		echo '&lt;/div&gt;';
	else :
		echo '&lt;div id="message" class="error"&gt;';
		echo '&lt;p&gt;There was an error.&lt;/p&gt;';
		echo '&lt;/div&gt;';
	endif;
endif;
</pre>
<p>First we make sure the action is set to remove and there is an id to build a small query with.</p>
<p>Next we store some user data and run the query. Users should only be able to delete lists that belong to them, using <code>$bp-&gt;loggedin_user-&gt;id</code> helps us achieve this.</p>
<p>Finally we serve a message depending on the outcome.</p>
<hr />
<h2><span>Conclusion</span></h2>
<p>Over the course of this tutorial a number of techniques have been applied. Using jQuery, raw PHP, WordPress conventions and BuddyPress we have been able to illustrate a nice feature to be added to your social network site powered by WordPress and BuddyPress.</p>
<p>Out of the box BuddyPress does not come with a bookmarks manager attached to member profiles and there isn't a plugin out there that functions exactly like this.</p>
<p>A bookmarks manager is one example but this could be anything.</p>
<p>The main goal of this tutorial was to illustrate how quickly and effectively you can hi-jack BuddyPress to demonstrate proof of concept.</p>
<p>With some know-how this could be put together in an evening with little trouble at all. The time commitment is tangible and could be factored into a monthly maintenance contract.</p>
<p>However if a client desired more features from the bookmarks manager such as a dashboard widget and more in-depth features you would be stepping into the realms of a plugin.</p>
<p>Data has not been sanitised in this tutorial so please make sure if you are to place this into a "real world" environment, go through <a href="http://wp.tutsplus.com/tutorials/creative-coding/data-sanitization-and-validation-with-wordpress/">a little bit of validation</a> before-hand.</p>
<p>I hope you have enjoyed this tutorial and any discrepancies you may find please do leave a comment and will do my best to help you through it.</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/plugins/fast-buddypress-development/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Data Sanitization and Validation With WordPress</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/data-sanitization-and-validation-with-wordpress/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/data-sanitization-and-validation-with-wordpress/#comments</comments>
		<pubDate>Tue, 29 May 2012 12:06:40 +0000</pubDate>
		<dc:creator>Stephen Harris</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[sanitisation]]></category>
		<category><![CDATA[validation]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25536</guid>
		<description><![CDATA[<p>Proper security is critical to keeping your site or that of your theme or plug-in users safe. Part of that means appropriate data validation and sanitization. In this article we are going to look at why this is important, what needs to be done, and what functions WordPress provides to help.<span id="more-25536"></span></p>
<p>Since there seem to be various interpretations of what the terms &#8216;validation&#8217;, &#8216;escaping&#8217; and &#8216;sanitization&#8217; mean, I&#8217;ll first clarify what I mean by them in this article:</p>
<ul>
<li><strong>Validation</strong> &ndash; These are the checks that are run to ensure the data you <em>have</em> is what it <em>should</em> be. For instance, that an e-mail looks like an e-mail address, that a date is a date and that a number is (or is cast as) an integer</li>
<li><strong>Sanitization / Escaping</strong> &ndash; These are the filters that are applied to data to make it &#8216;safe&#8217; in a specific context. For instance, to display HTML code in a text area it would be necessary to replace all the HTML tags by their entity equivalents</li>
</ul>
<hr />
<h2>Why Is Sanitization Important?</h2>
<p>When data is included in some context (say in a HTML document) &ndash; that data could be misinterpreted as a code for that environment (for example HTML code). If that data contains malicious code, then using that data without sanitizing it, means that code will be executed. The code doesn&#8217;t even necessarily have to be malicious for it to cause undesired effects. The job of sanitization is to make sure that any code in the data isn&#8217;t interpreted as code &ndash; otherwise you may end up like Bobby Tables&#8217; school&#8230;</p>
<div class="tutorial_image">
	<img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" border="0"></p>
<p><em><a href="http://xkcd.com/327/">&#8216;Exploits of a Mom&#8217; &#8211; xkcd</a></em></p>
</div>
<p>A seemingly innocuous example might be pre-filling a search field with the currently queried term, using the unescaped <code>$_GET['s']</code>:</p>
<pre name="code" class="php">
&lt;form method="get" id="searchform" action="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;"&gt;
	&lt;input type="text" class="field" name="s" id="s" value="&lt;?php echo $_GET['s']; ?&gt;"/&gt;
	&lt;input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" /&gt;
&lt;/form&gt;
</pre>
<p>This opens up a vulnerability that could allow javascript to be injected by, for instance, tricking someone into visiting <code>http://yoursite.com?s="/&gt;&lt;script&gt;alert('Injected javascript')&lt;/script&gt;</code>. The search term &#8216;jumps&#8217; out of the value attribute, and the following part of the data is interpreted as code and executed. To prevent this, WordPress provides <a href="http://queryposts.com/function/get_search_query/"><code>get_search_query</code></a> which returns the sanitized search query. Although this is a &#8216;harmless&#8217; example the injected script could be far more malicious and at best it would just &#8216;break&#8217; the form if search terms contain double quotes.</p>
<p>How this malicious (or otherwise) code may have found its way onto your site is not the concern here &ndash; but rather it is to prevent it from executing. Nor do we make assumptions about the nature of this unwanted code, or its intent &ndash; it could have simply been an error on the user&#8217;s part. This brings me to rule No.1&#8230;</p>
<hr />
<h2>Rule No. 1: Trust Nobody</h2>
<p>It&#8217;s a common maxim that is used with regards to data sanitization, and it&#8217;s a good one. The idea is that you should not assume that any data entered by the user is safe. Nor should you assume that the data you&#8217;ve retrieved from the database is safe &ndash; even if you had made it &#8216;safe&#8217; prior to inserting it there. In fact, whether data can be considered &#8216;safe&#8217; makes no sense without context. Sometimes the same data may be used in multiple contexts on the same page. Titles for instance, can safely contain quotes or double quotes when inside header tags &ndash; but will cause problems if used (unescaped) inside a title attribute of a link tag. So it is rather pointless to make data &#8216;safe&#8217; when adding it to the database, since it is often impossible to make data safe for all contexts simultaneously. (Of course it needs to be made safe to add to the database &ndash; but we&#8217;ll come to that later).</p>
<p>Even if you only intend to use that data in one specific context, say a form, it is still pointless to sanitize the data when writing to the database because, as per Rule No. 1, you cannot trust that it is still safe when you take it out again.</p>
<hr />
<h2>Rule No. 2: Validate on Input, Escape on Output</h2>
<p>This is the procedural maxim that sets out when you should validate data, and when you sanitize it. Simply put &ndash; validate your data (check it&#8217;s what it should be &ndash; and that it&#8217;s &#8216;valid&#8217;) as soon as you receive it from the user. When you come to use this data, for example when you output it, you need to escape (or sanitize) it. What form this sanitization takes, depends entirely on the context you are using it in.</p>
<p>The best advice is to perform this &#8216;late&#8217;: escape your data immediately before you use or display it. This way you can be confident that your data has been properly sanitized and you don&#8217;t need to remember if the data has been previously checked.</p>
<hr />
<h2>Rule No. 3: Trust WordPress</h2>
<p>You might be thinking &#8220;Ok, validate before writing to database and sanitize when using it. But don&#8217;t I need to make sure the data is safe to write to the database?&#8221;. In general, <strong>yes</strong>. When adding data to a database, or simply using an input to interact with a database, you would need to escape the data incase it contained any SQL commands. But this brings me to Rule No. 3, one which flies in the face of Rule No. 1: Trust WordPress.</p>
<p>In a previous article, I took user input (sent from a search form via AJAX) and used it directly with <code>get_posts()</code> to return posts that matched that search query:</p>
<pre name="code" class="php">
	$posts = get_posts( array(
		's'=&gt;$_REQUEST['term']
	) );
</pre>
<p>An observant reader noticed that I hadn&#8217;t performed any sanitization &ndash; and they were right. But I didn&#8217;t need to. When you use high-level functions such as <code>get_posts()</code>, you don&#8217;t need to worry about sanitizing the data &ndash; because the database queries are all properly escaped by WordPress&#8217; internals. It&#8217;s a different matter entirely if you are using a direct SQL query &ndash; but we&#8217;ll look at this in a later section. Similarly, functions like <a href="http://codex.wordpress.org/Function_Reference/the_title"><code>the_title()</code></a>, <a href="http://codex.wordpress.org/Function_Reference/the_permalink"><code>the_permalink()</code></a>, <a href="http://codex.wordpress.org/Function_Reference/the_content"><code>the_content()</code></a> etc. perform their own sanitization (for the appropriate context).</p>
<hr />
<h2>Data Validation</h2>
<p>When you receive data entered by a user it&#8217;s important to <em>validate</em> it. (The settings API, <a href="http://wp.tutsplus.com/series/the-complete-guide-to-the-wordpress-settings-api/">covered in this series</a>, allows you to specify a callback function to do exactly this). Invalid data is either auto-corrected, or the process is aborted and the user is returned to the form to try again (hopefully with an appropriate error message). The concern here is not safety but rather validity &ndash; if you&#8217;re doing it right, WordPress will take care of safely adding the data to the database. What &#8216;valid&#8217; means is up to you &ndash; it could mean a valid email address, a positive integer, text of a limited length, or one of an array of specified options. However you aim to determine validity, WordPress offers a lot of functions that can help.</p>
<h3>Numbers</h3>
<p>When expecting numeric data, it&#8217;s possible to check if the data &#8216;is some form of number&#8217;, for instance <a href="http://php.net/manual/en/function.is-int.php"><code>is_int</code></a> or <a href="http://php.net/manual/en/function.is-float.php"><code>is_float</code></a>. Usually, it&#8217;s sufficient to simply cast the data as numeric with: <a href="http://php.net/manual/en/function.intval.php"><code>intval</code></a> or <a href="http://php.net/manual/en/function.floatval.php"><code>floatval</code></a>.</p>
<p>If you need to ensure the number is padded with leading zeros, WordPress provides the function <a href="http://codex.wordpress.org/Function_Reference/zeroise"><code>zeroise()</code></a>. Which takes the following parameters:</p>
<ul>
<li><strong>Number</strong> &ndash; the number to pad</li>
<li><strong>Threshold</strong> &ndash; the number of digits the number will be padded to</li>
</ul>
<p>For example:</p>
<pre name="code" class="php">
echo zeroise(70,4); // Prints 0070
</pre>
<h3>E-mails</h3>
<p>To check the validity of e-mails, WordPress has the <a href="http://codex.wordpress.org/Function_Reference/is_email"><code>is_email()</code></a> function. This function uses simple checks to validate the address. For instance, it checks that it contains the &#8216;@&#8217; symbol, that it&#8217;s longer than 3 characters, the domain contains only alpha-numerics and hyphens, and so forth. Obviously, it doesn&#8217;t check that the e-mail address actually exists. Assuming the e-mail address passed the checks, it is returned, otherwise &#8216;false&#8217; is returned.</p>
<pre name="code" class="php">
	$email = is_email('someone@e^ample.com');
	// $email is set to false.

	$email = is_email('someone@example.com');
	// $email is set to 'someone@example.com'.
</pre>
<h3>HTML</h3>
<p>Often you may wish to allow only <em>some</em> HTML tags in your data &ndash; for instance in comments posted on your site. WordPress provides a family of functions of the form <a href="http://codex.wordpress.org/Function_Reference/wp_kses"><code>wp_kses_*</code></a> (KSES Strips Evil Scripts). These functions remove (some subset of) HTML tags, and can be used to ensure that links in the data are of specified protocols. For example the <a href="http://codex.wordpress.org/Function_Reference/wp_kses"><code>wp_kses()</code></a> function accepts three arguments:</p>
<ul>
<li><code>content</code> &ndash; (string) Content to filter through kses</li>
<li><code>allowed_html</code> &ndash; An array where each key is an allowed HTML element and the value is an array of allowed attributes for that element</li>
<li><code>allowed_protocols</code> &ndash; Optional. Allowed protocol in links (for example <code>http</code>, <code>mailto</code>, <code>feed</code> etc.)</li>
</ul>
<p><code>wp_kses()</code> is a very flexible function, allowing you to remove unwanted tags, or just unwanted attributes from tags. For example, to only allow <code>&lt;strong&gt;</code> or <code>&lt;a&gt;</code> tags (but only allow the href attribute):</p>
<pre name="code" class="php">
$content = "&lt;em&gt;Click&lt;/em&gt; &lt;a title='click for wp.tuts+' href='http://wp.tutsplus.com'&gt;here&lt;/a&gt; to visit &lt;strong&gt; wptuts+ &lt;/strong&gt;";

echo wp_kses( $content, array(
	'strong' =&gt; array(),
	'a' =&gt; array('href')
) );

// Prints the HTML "Click &lt;a href='http://wp.tutsplus.com'&gt;here&lt;/a&gt; to visit &lt;strong&gt; wptuts+ &lt;/strong&gt;":
Click <a href="http://wp.tutsplus.com">here</a> to visit <strong> wptuts+ </strong>
</pre>
<p>Of course, specifying every allowed tag and every allowed attribute can be a laborious task. So WordPress provides other functions that allow you to use <code>wp_kses</code> with pre-set allowed tags and protocols &ndash; namely the ones used for validating posts and comments:</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_kses_post"><code>wp_kses_post()</code></a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_kses_data"><code>wp_kses_data()</code></a></li>
</ul>
<p>The above functions are helpful in ensuring that HTML received from the user only contains whitelisted elements. Once we&#8217;ve done that we would also like to ensure that each tag is balanced, that is every opening tag has its corresponding closing tag. For this we can use <a href="http://codex.wordpress.org/Function_Reference/balanceTags"><code>balanceTags()</code></a>. This function accepts two arguments:</p>
<ul>
<li><strong>content</strong> &ndash; Content to filter and balance tags of</li>
<li><strong>force balance</strong> &ndash; True or false, whether to force the balancing of tags</li>
</ul>
<pre name="code" class="php">
// Content with missing closing &lt;/strong&gt; tag
$content = "&lt;em&gt;Click&lt;/em&gt; &lt;a href='http://wp.tutsplus.com'&gt;here&lt;/a&gt; to visit &lt;strong&gt; wptuts+";

echo balanceTags($content,true),

// Prints the HTML "Click &lt;a href='http://wp.tutsplus.com'&gt;here&lt;/a&gt; to visit &lt;strong&gt; wptuts+ &lt;/strong&gt;"
</pre>
<h3>Filenames</h3>
<p>If you want to create a file in one of your website&#8217;s directories, you will want to ensure the filename is both valid and legal. You would also want to ensure that the filename is unique for that directory. For this WordPress provides:</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/sanitize_file_name"><code>sanitize_file_name( $filename )</code></a> &ndash; sanitizes (or validates) the file-name by removing characters that are illegal in filenames on certain operating systems or that would require escaping at the command line. Replaces spaces with dashes and consecutive dashes with a single dash and removes periods, dashes and underscores from the beginning and end of the filename.</li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_unique_filename"><code>wp_unique_filename( $dir, $filename )</code></a> &ndash; returns a unique (for directory <code>$dir</code>), sanitized filename (it uses <code>sanitize_file_name</code>).</li>
</ul>
<h3>Data From Text Fields</h3>
<p>When receiving data inputted into a text field, you&#8217;ll probably want to strip out extra white spaces, tabs and line breaks, as well as stripping out any tags. For this WordPress provides <a href="http://queryposts.com/function/sanitize_text_field/"><code>sanitize_text_field()</code></a>.</p>
<h3>Keys</h3>
<p>WordPress also provides <a href="http://queryposts.com/function/sanitize_key/"><code>sanitize_key</code></a>. This is a very generic (and occasionally useful) function. It simply ensures the returned variable contains only lower-case alpha-numerics, dashes, and underscores.</p>
<hr />
<h2>Data Sanitization</h2>
<p>Whereas validation is concerned with making sure data is valid &ndash; data sanitization is about making it <em>safe</em>. While some of the validation functions referred to above might be useful in making sure data is safe &ndash; in general, it is not sufficient. Even &#8216;valid&#8217; data might be unsafe in certain contexts.</p>
<hr />
<h2>Rule No. 4: Making Data Safe Is About Context</h2>
<p>Simply put you cannot ask <em>&#8220;How do I make this data safe?&#8221;</em>. Instead you should ask, <em>&#8220;How do I make this data safe for using it in X&#8221;</em>.</p>
<p>To illustrate this point, suppose you have a widget with a textarea where you intend to allow the user to enter some HTML. Suppose they then enter:</p>
<pre name="code" class="php">
&lt;textarea name="my-textarea"&gt;&lt;/textarea&gt; Hello World
</pre>
<p>This is perfectly valid, and safe, HTML &ndash; however when you click save, we find that the text has jumped out of the textarea. The HTML code is not safe as a value for the textarea:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/285_Data_Sanitisation_and_Validation_With_WordPress/1.png" border="0"></div>
<p>What is safe to use in one context, is not necessarily safe in another. Whenever you use or display data you must keep in mind what forms of sanitization need to be done in order to make using that data safe. This is why WordPress often provides several functions for the same content, for instance:</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/the_title"><code>the_title</code></a> &ndash; for using the title in standard HTML (inside header tags, for example)</li>
<li><a href="http://codex.wordpress.org/Function_Reference/the_title_attribute"><code>the_title_attribute</code></a> &ndash; for using the title as an attribute value (usually the title attribute in <code>&lt;a&gt;</code> tags)</li>
<li><a href="http://codex.wordpress.org/Function_Reference/get_the_title_rss"><code>the_title_rss</code></a> &ndash; for using the title in RSS feeds</li>
</ul>
<p>These all perform the necessary sanitization for a particular context &ndash; and if you&#8217;re using them you should be sure to use the correct one. Sometimes though, we&#8217;ll need to perform our own sanitization &ndash; often because we have custom input beyond the standard post title, permalink, content etc. that WordPress handles for us.</p>
<h3>Escaping HTML</h3>
<p>When printing variables to the page we need to be mindful of how the browser will interpret them. Let&#8217;s consider the following example:</p>
<pre name="code" class="php">
&lt;h1&gt; &lt;?php echo $title; ?&gt; &lt;/h1&gt;
</pre>
<p>Suppose <code>$title = &lt;script&gt;alert('Injected javascript')&lt;/script&gt;</code>. Rather than displaying the HTML <code>&lt;script&gt;</code> tags, they will be interpreted as HTML and the enclosed javascript would be injected into the page.</p>
<p>This form of injection (as also demonstrated in the search form example) is called <strong>Cross-site scripting</strong> and this benign example belies its severity. Injected script can essentially control the browser and &#8216;act on behalf&#8217; of the user or steal the user&#8217;s cookies. This becomes an even more serious issue if the user is logged in. To prevent variables printed inside HTML being interpreted as HTML, WordPress provides the well known <a href="http://codex.wordpress.org/Function_Reference/esc_html"><code>esc_html</code></a> function. In this example:</p>
<pre name="code" class="php">
&lt;h1&gt; &lt;?php echo esc_html($title); ?&gt; &lt;/h1&gt;
</pre>
<h3>Escaping Attributes</h3>
<p>Now consider the following example:</p>
<pre name="code" class="php">
&lt;?php $value = 'my-value" onfocus="alert(\"Injected javascript\")"'; ?&gt;
&lt;input type="text" name="myInput" value="&lt;?php echo $value;?&gt;"/&gt;
</pre>
<p>Because <code>$value</code> contains double quotes, unescaped it can jump out of the value attribute and inject script, for example, by using the <code>onfocus</code> attribute. To escape unsafe characters (such as quotes, and double-quotes in this case), WordPress provides the function <a href="http://codex.wordpress.org/Function_Reference/esc_attr"><code>esc_attr</code></a>. Like <code>esc_html</code> it replaces &#8216;unsafe&#8217; characters by their entity equivalents. In fact, at the time of writing, these functions are identical &ndash; but you should still use the one that is appropriate for the context.</p>
<p>For this example we should have:</p>
<pre name="code" class="php">
&lt;?php $value = 'my-value" onfocus="alert(\"Injected javascript\")"'; ?&gt;
&lt;input type="text" name="myInput" value="&lt;?php echo esc_attr($value);?&gt;"/&gt;
</pre>
<p>Both <code>esc_html</code> and <code>esc_attr</code> also come with <code>__</code>, <code> _e</code>, and <code>_x</code> variants.</p>
<ul>
<li><code>esc_html__('Text to translate', 'plugin-domain')</code> / <code>esc_attr__</code> &ndash; returns the escaped translated text,</li>
<li><code>esc_html_e('Text to translate', 'plugin-domain')</code> / <code>esc_attr_e</code> &ndash; displays the escaped translated text and finally the</li>
<li><code>esc_html_x('Text to translate', $context, 'plugin-domain')</code> / <code>esc_attr_x</code> &ndash; translates the text according to the passed context, and then returns the escaped translation</li>
</ul>
<h3>HTML Class Names</h3>
<p>For class names, WordPress provides <a href="http://queryposts.com/function/sanitize_html_class/"><code>sanitize_html_class</code></a> &ndash; this escapes variables for use in class names, simply by restricting the returned value to alpha-numerics, hyphens and underscores. Note: It does not ensure the class name is <em>valid</em> (reference: <a href="http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier">http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier</a>).</p>
<blockquote>
<p>In CSS, identifiers can contain only the characters <code>[a-zA-Z0-9]</code> and ISO 10646 characters U+00A0 and higher, plus the hyphen (<code>-</code>) and the underscore (<code>_</code>); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code.</p>
</blockquote>
<h3>Escaping URLs</h3>
<p>Let&#8217;s now look at another common practise, printing variables into the <code>href</code> attribute:</p>
<pre name="code" class="php">
&lt;a href="&lt;?php echo $url;?&gt;" title="Link Title"&gt; Link Text &lt;/a&gt;
</pre>
<p>Clearly it is vulnerable to the same form of attack as illustrated in escaping HTML and attributes. But what if the <code>$url</code> was set as follows:</p>
<pre name="code" class="php">
$url = 'javascript:alert(\'Injected javascript\')'
</pre>
<p>On clicking the link, the alert function would be fired. This contains no HTML, or any quotes that allow it to jump out of the href attribute &ndash; so <code>esc_attr</code> is not sufficient here. This is why context matters: <code>esc_attr($url)</code> would be safe in the <code>title</code> attribute, but not for the <code>href</code> attribute &ndash; and this is because of the javascript protocol &ndash; which while perfectly <em>valid</em> &ndash; is not to be considered safe in this context. Instead you should use:</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/esc_url"><code>esc_url</code></a> &ndash; for escaping URLs that will be printed to the page.</li>
<li><a href="http://codex.wordpress.org/Function_Reference/esc_url_raw"><code>esc_url_raw</code></a> &ndash; for escaping URLs to save to the database or use in URL redirecting.</li>
</ul>
<p><code>esc_url</code> strips out various offending characters, and replaces quotes and ampersands with their entity equivalents. It then checks that the protocol being used is allowed (javascript, by default, isn&#8217;t).</p>
<p>What <code>esc_url_raw</code> does is almost identical to <code>esc_url</code>, but it does not replace ampersands and single quotes (which you don&#8217;t want to, when using the URL as an URL, rather than displaying it).</p>
<p>In this example, we are <em>displaying</em> the URL, so we use <code>esc_url:</code></p>
<pre name="code" class="php">
&lt;a href="&lt;?php echo esc_url($url);?&gt;" title="Link Title"&gt; Link Text &lt;/a&gt;
</pre>
<p>Although not necessary in most cases, both functions accept an optional array to specify which protocols (such as <code>http</code>, <code>https</code>, <code>ftp</code>, <code>ftps</code>, <code>mailto</code>, etc) you wish to allow.</p>
<h3>Escaping JavaScript</h3>
<p>Sometimes you&#8217;ll want to print javascript variables to a page (usually in the head):</p>
<pre name="code" class="php">
&lt;script&gt;
var myVar = '&lt;?php echo $variable; ?&gt;';
&lt;/script&gt;
</pre>
<p>In fact, if you are doing this, you should almost certainly be using <a href="http://codex.wordpress.org/Function_Reference/wp_localize_script"><code>wp_localize_script()</code></a> &ndash; which handles sanitization for you. (If anyone can think of a reason why you might need to use the above method instead, I would like to hear it).</p>
<p>However, to make the above example safe, you can use the <a href="http://queryposts.com/function/esc_js/"><code>esc_js</code></a> function:</p>
<pre name="code" class="php">
&lt;script&gt;
var myVar = '&lt;?php echo esc_js($variable); ?&gt;';
&lt;/script&gt;
</pre>
<h3>Escaping Textarea</h3>
<p>When displaying content in a textarea, <code>esc_html</code> is not sufficient because it <em>does not double encode entities</em>. For example:</p>
<pre name="code" class="php">
&lt;?php $var = '&lt;strong&gt;text&lt;/strong&gt; &amp;lt;b&amp;gt;bold&amp;lt;/b&amp;gt;' ?&gt;
&lt;textarea&gt;&lt;?php echo esc_html($var); ?&gt; &lt;/textarea&gt;
</pre>
<p><code>$var</code> printed in the textarea will appear as:</p>
<pre name="code" class="php">
&lt;strong&gt;text&lt;/strong&gt; &lt;b&gt;bold&lt;/b&gt;
</pre>
<p>Rather than also encoding the <code>&amp;</code> as <code>&amp;amp;</code> in the <code>&lt;b&gt;</code> tags.</p>
<p>For this WordPress provides <a href="http://codex.wordpress.org/Function_Reference/esc_textarea"><code>esc_textarea</code></a>, which is almost identical to <code>esc_html</code>, but does double encode entities. Essentially it is little more than a wrapper for <a href="http://php.net/manual/en/function.htmlspecialchars.php"><code>htmlspecialchars</code></a>. In this example:</p>
<pre name="code" class="php">
&lt;?php $var = '&lt;strong&gt;text&lt;/strong&gt; &amp;lt;b&amp;gt;bold&amp;lt;/b&amp;gt;' ?&gt;
&lt;textarea&gt;&lt;?php echo esc_textarea($var); ?&gt; &lt;/textarea&gt;
</pre>
<h3>Antispambot</h3>
<p>Displaying e-mail addresses on your website leaves them prone to e-mail harvesters. One simple method is to disguise the e-mail address. WordPress provides <a href="http://codex.wordpress.org/Function_Reference/antispambot"><code>antispambot</code></a>, which encodes random parts of the e-mail address into their HTML entities (and hexadecimal equivalents if <code>$mailto = 1</code>). On each page load the encoding should be different and while the returned address renders correctly in the browser, it should appear as gobbledygook to the spambots. The function accepts two arguments:</p>
<ul>
<li><code>e-mail</code> &ndash; the address to obfuscate</li>
<li><code>mailto</code> &ndash; 1 or 0 (1 if using the mailto protocol in a link tag)</li>
</ul>
<pre name="code" class="php">
$email = "joebloggs@example.com";
$email = sanitize_email($email);
echo '&lt;a href="mailto:'.antispambot($email,1).'" title="Click to e-mail me" &gt;'.antispambot($email).' &lt;/a&gt;';
</pre>
<h3>Query Strings</h3>
<p>If you wish to add (or remove) variables from a query string (this is very useful if you wish to allow users to select an order for your posts), the safest and easiest way is to use <a href="http://codex.wordpress.org/Function_Reference/add_query_arg"><code>add_query_arg</code></a> and <a href="http://codex.wordpress.org/Function_Reference/remove_query_arg"><code>remove_query_arg</code></a>. These functions handle all the necessary escaping for for the arguments and their values for use in the URL.</p>
<p><code>add_query_arg</code> accepts two arguments:</p>
<ul>
<li><code>query parameters</code> &ndash; an associative array of parameters -&gt; values</li>
<li><code>url</code> &ndash; the URL to add the parameters and their values to. If omitted, the URL of the current page is used</li>
</ul>
<p><code>remove_query_arg</code> also accepts two arguments, the first is an array of parameters to remove, the second is as above.</p>
<pre name="code" class="php">
// If we are at www.example.com/wp-admin/edit.php?post_type=book
$query_params = array ('page' =&gt; 'my-bage');
$url = add_query_arg( $query_params );

// Would set $url to be:
// www.example.com/wp-admin/edit.php?post_type=book&amp;page=my-page
</pre>
<hr />
<h2>Validation &amp; Sanitization</h2>
<p>As previously mentioned, sanitization doesn&#8217;t make much sense without a context &ndash; so it&#8217;s pretty pointless to sanitize data when writing to the database. Often, you need to store data in its raw format anyway, and in any case &ndash; Rule No. 1 dictates that we should always sanitize on output.</p>
<p>Validation of data, on the other hand, should be done as soon as it&#8217;s received and before it&#8217;s written to the database. The idea is that &#8216;invalid&#8217; data should either be auto-corrected, or be flagged to the data, and only valid data should be given to the database.</p>
<p>That said &ndash; you may want to also perform validation when data is displayed too. In fact sometimes, &#8216;validation&#8217; will also ensure the data is safe. But the priority here is on safety and you should avoid excessive validation that would run on every page load (the <code>wp_kses_*</code> functions, for instance, are very expensive to perform).</p>
<hr />
<h2>Database Escaping</h2>
<p>When using functions such as <code>get_posts</code> or classes such as <code>WP_Query</code> and <code>WP_User_Query</code>, WordPress takes care of the necessary sanitization in querying the database. However, when retrieving data from a custom table, or otherwise performing a direct SQL query on the database &ndash; proper sanitization is then up to you. WordPress, however, provides a helpful class, the <a href="http://codex.wordpress.org/Class_Reference/wpdb"><code>$wpdb</code></a> class, that helps with escaping SQL queries.</p>
<p>Let&#8217;s consider this basic &#8216;<code>SELECT</code>&#8216; command, where <code>$age</code> and <code>$firstname</code> are variables storing an age and name that we are querying:</p>
<pre name="code" class="php">
SELECT * WHERE age='$age' AND firstname = '$firstname'
</pre>
<p>We have not escaped these variables, so potentially further commands could be injected in. Borrowing xkcd&#8217;s example from above:</p>
<pre name="code" class="php">
$age = 14;
$firstname = "Robert'; DROP TABLE Students;";
$sql = "SELECT * WHERE age='$age' AND firstname = '$firstname';";
$results = $wpdb->query
</pre>
<p>Will run as the command(s):</p>
<pre name="code" class="php">
SELECT * WHERE age='14' AND firstname = 'Robert'; DROP TABLE Students;';
</pre>
<p>And delete our entire Students table.</p>
<p>To prevent this, we can use the <code>$wpdb-&gt;prepare</code> method. This accepts two parameters:</p>
<ul>
<li>The SQL command as a string, where string variables are replaced by the placeholder <code>%s</code> and decimal numbers are replaced by the placeholder <code>%d</code> and floats by <code>%f</code></li>
<li>An array of values for the above placeholders, in the order they appear in the query</li>
</ul>
<p>In this example:</p>
<pre name="code" class="php">
$age = 14;
$firstname = "Robert'; DROP TABLE Students;";
$sql = $wpdb-&gt;prepare('SELECT * WHERE age=%d AND firstname = %s;',array($age,$firstname));
$results = $wpdb-&gt;get_results($sql);
</pre>
<p>The escaped SQL query (<code>$sql</code> in this example) can then be used with one of the methods:</p>
<ul>
<li><code>$wpdb-&gt;get_row($sql)</code></li>
<li><code>$wpdb-&gt;get_var($sql)</code></li>
<li><code>$wpdb-&gt;get_results($sql)</code></li>
<li><code>$wpdb-&gt;get_col($sql)</code></li>
<li><code>$wpdb-&gt;query($sql)</code></li>
</ul>
<h3>Inserting and Updating Data</h3>
<p>For inserting or updating data, WordPress makes life even easier by providing the <code>$wpdb-&gt;insert()</code> and <code>$wpdb-&gt;update()</code> methods.</p>
<p>The <code>$wpdb-&gt;insert()</code> method accepts three arguments:</p>
<ul>
<li><strong>Table name</strong> &ndash; the name of the table</li>
<li><strong>Data</strong> &ndash; array of data to insert as column-&gt;value pairs</li>
<li><strong>Formats</strong> &ndash; array of formats for the corresponding values (&#8216;<code>%s</code>&#8216;,&#8217;<code>%d</code>&#8216; or&#8217;<code>%f</code>&#8216;)</li>
</ul>
<pre name="code" class="php">
$age = 14;
$firstname = "Robert'; DROP TABLE Students;";
$wpdb-&gt;insert(
	'Students',
	array( 'firstname' =&gt; $firstname, 'age' =&gt; $age ),
	array( '%s', '%d' )
);
</pre>
<p>The <code>$wpdb-&gt;update()</code> method accepts five arguments:</p>
<ul>
<li><strong>Table name</strong> &ndash; the name of the table</li>
<li><strong>Data</strong> &ndash; array of data to update as column-&gt;value pairs</li>
<li><strong>Where</strong> &ndash; array of data to match as column-&gt;value pairs</li>
<li><strong>Data Format</strong> &ndash; array of formats for the corresponding data values</li>
<li><strong>Where Format</strong> &ndash; array of formats for the corresponding &#8216;where&#8217; values</li>
</ul>
<pre name="code" class="php">
// Update Robert'; DROP TABLE Students; to Bobby

$oldname = "Robert'; DROP TABLE Students;";
$newname = "Bobby";
$wpdb-&gt;update(
	'Students',
	array( 'firstname' =&gt; $newname ),
	array( 'firstname' =&gt; $oldname ),
	array( '%s' ),
	array( '%s' )
);
</pre>
<p>Both the <code>$wpdb-&gt;insert()</code> and the <code>$wpdb-&gt;update()</code> methods perform all the necessary sanitization for writing to the database.</p>
<h3>Like Statements</h3>
<p>Because the <code>$wpdb-&gt;prepare</code> method uses <code>%</code> to distinguish the place-holders, care needs to be taken when using the <code>%</code> wildcard in SQL LIKE-statements. The Codex suggests escaping them with a second <code>%</code>. Alternatively you can escape the term to be searched for with <a href="http://queryposts.com/function/like_escape/"><code>like_escape</code></a> and then add the wildcard <code>%</code> where appropriate, before including this in the query using the prepare method. For instance:</p>
<pre name="code" class="php">
$age=14;
$firstname = "Robert'; DROP TABLE Students;";
SELECT * WHERE age=$age (firstname LIKE '%$firstname%');
</pre>
<p>Would be made safe with:</p>
<pre name="code" class="php">
$age=14;
$firstname = "Robert'; DROP TABLE Students;";
SELECT * WHERE age=$age AND (firstname LIKE '%$firstname%');
$query = $wpdb-&gt;prepare('SELECT * WHERE age=%d AND (firstname LIKE %s);', array($age, '%'.like_escape($firstname).'%') );
</pre>
<hr />
<h2>Summary</h2>
<p>This isn&#8217;t an exhaustive list of the functions available for validation and sanitization, but it should cover the vast majority of use cases. A lot of these (and other) functions can be found in <a href="core.trac.wordpress.org/browser/trunk/wp-includes/formatting.php"><code>/wp-includes/formatting.php</code></a> and I&#8217;d strongly recommend digging into the core code and having a look into how WordPress core does validation and sanitization of data.</p>
<p>Did you find this article useful? Do you have any further suggestions on best practices for data validation and sanitization in WordPress? Let us know in the comments below.</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/data-sanitization-and-validation-with-wordpress/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Function Examination: wp_nav_menu</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/function-examination-wp_nav_menu/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/function-examination-wp_nav_menu/#comments</comments>
		<pubDate>Mon, 28 May 2012 10:11:45 +0000</pubDate>
		<dc:creator>Tammy Hart</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[functional examination]]></category>
		<category><![CDATA[wp_nav_menu]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25525</guid>
		<description><![CDATA[<p>When WordPress 3 presented us with the new Menus functionality, it changed the way we viewed navigation menus forever. No longer were we bound to using the normal page listing functions or building our own custom menu functions to integrate category and page menus as well as external or hard linked items within a nav menu. But just how custom can we get with this new functionality? In this tutorial, we&#8217;ll dive deep into everything that the <code>wp_nav_menu</code> function can do, use the <a href="http://wp.tutsplus.com/tutorials/creative-coding/understanding-the-walker-class/">Walker Class</a> to add a sub description, and touch on some of its related functions.<span id="more-25525"></span></p>
<hr />
<h2>The Parameters</h2>
<p>The function has several parameters to work with. Here are the defaults as listed in the <a href="http://codex.wordpress.org/Function_Reference/wp_nav_menu">WordPress.org Codex</a>:</p>
<pre name="code" class="php">
&lt;?php $defaults = array(
	'theme_location'  =&gt; ,
	'menu'            =&gt; ,
	'container'       =&gt; 'div',
	'container_class' =&gt; 'menu-{menu slug}-container',
	'container_id'    =&gt; ,
	'menu_class'      =&gt; 'menu',
	'menu_id'         =&gt; ,
	'echo'            =&gt; true,
	'fallback_cb'     =&gt; 'wp_page_menu',
	'before'          =&gt; ,
	'after'           =&gt; ,
	'link_before'     =&gt; ,
	'link_after'      =&gt; ,
	'items_wrap'      =&gt; '&lt;ul id=\&quot;%1$s\&quot; class=\&quot;%2$s\&quot;&gt;%3$s&lt;/ul&gt;',
	'depth'           =&gt; 0,
	'walker'          =&gt;
);
?&gt;

&lt;?php wp_nav_menu( $defaults ); ?&gt;
</pre>
<h3>Theme Location</h3>
<p>Using this parameter, we can set a theme location which is then used on the Menus page to set a menu to work in that part of your theme, without having to manually define which menu should appear there. This is very helpful for theme distributors because you&#8217;re able to use conditionals to display a menu only if the user has defined a menu for that location. The only other requirement is that you use the function <code>register_nav_menu()</code> to register those locations. This is usually done from your function files when you&#8217;re setting up support for menus.</p>
<p>Let&#8217;s start building our custom menu function parameters assuming that we&#8217;ve registered a theme location called &quot;<code>primary</code>&quot;.</p>
<pre name="code" class="php">
$params = array(
	'theme_location' =&gt; 'primary'
);
</pre>
<h3>Menu</h3>
<p>This parameter is used to manually define which menu should be used. In our example, we are only setting a generic menu location and not defining an exact one to use, but if we were wanting to tell the function to use a menu called &quot;Primary Navigation&quot;, our parameters would look like this:</p>
<pre name="code" class="php">
$params = array(
	'theme_location' =&gt; 'primary',
	'menu' =&gt; 'Primary Navigation'
);
</pre>
<h3>Container</h3>
<p>By default, our menu will be wrapped in a <code>div</code>, but if you&#8217;re like me, you usually don&#8217;t need this and probably want to cut back on the amount of <code>div</code>s and other tags being used to keep your code as tidy as possible. You could also use this parameter to define a different tag such as an html5 <code>&lt;section&gt;</code> or <code>&lt;nav&gt;</code>. For our example, we don&#8217;t want a container to change the default container values since the Twenty Eleven theme styles rely on it being there.</p>
<h3>Container Class and Container ID</h3>
<p>As you can pretty much guess, these parameters are used to set a class and an ID to the container. Since we&#8217;re omitting this altogether, we have no need to define values.</p>
<h3>Menu Class and Menu ID</h3>
<p>These work just like the previous parameters except this time we definitely want to set an ID of &quot;<code>nav</code>&quot; because that is the ID we&#8217;ll use in our stylesheet to style the navigation bar.</p>
<pre name="code" class="php">
$params = array(
	'theme_location' =&gt; 'primary',
	'container' =&gt; false,
	'menu_id' =&gt; 'nav'
);
</pre>
<h3>Echo</h3>
<p>You can use this parameter to tell whether you want to display (echo) the results, or return it for use in PHP. This item is boolean so to return it simply set this parameter to 0.</p>
<h3>Fallback CB</h3>
<p>This is a callback function that you can fallback to if no menu is found. By default it uses the old stand by <code>wp_page_menu()</code> and passes all of the same parameters to this function as well.</p>
<h3>Before and After</h3>
<p>These items are used to define what can be placed before and after the anchor tags (<code>&lt;a&gt;&lt;/a&gt;</code>). You could use these to precede each item with a vertical bar, or wrap the nav items in a span tag.</p>
<h3>Link Before and Link After</h3>
<p>These work the same as the previous items we covered except that whatever you define will be inside of the anchor tags. Our example doesn&#8217;t require that we use these so we&#8217;ll ignore them and let the default empty item be.</p>
<h3>Items Wrap</h3>
<p>By default, the items are wrapped in an unordered list with the menu id and menu class. This parameter lets you change that if you so desire.</p>
<h3>Depth</h3>
<p>This parameter is really nice for when you want to use the same menu twice but don&#8217;t want any child items to display in the location you&#8217;re setting up with the <code>wp_nav_menu()</code> function. For instance, if you want the primary navigation to include a second level dropdown, you could leave this at the default setting. Then if you wanted to use the same parent items in a footer navigation and omit the child items, you could set this parameter to a depth of 1. The default &quot;0&quot; means all levels will be output. To keep our example concise, we&#8217;re assuming that the primary navigation doesn&#8217;t include any child items.</p>
<h3>Walker</h3>
<p>The parameter is used to define a walker object which can be used to manipulate how the entire function works and outputs its information. We&#8217;ll go over a good example in the next section.</p>
<hr />
<h2>Adding a Description to the Nav Menu Items</h2>
<p>For our example, we want to add a sub description to each main menu item. The functionality to add the description itself is already in place in the WordPress Menu system. To turn this on, go to Menus and then press the screen options tab in the top right corner. The option you need to make sure is clicked should say, &quot;Description&quot;. With this checked, a menu item should now look like this:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/284_wp_nav_menu/wp_nav_menu2.jpg" width="424" height="310" /></div>
<p>Once we have our descriptions filled out, we&#8217;ll need to create the walker class and add it to the <code>wp_nav_menu()</code> parameters. We&#8217;ll call the class <code>description_navigation</code> so our complete parameters code should look like this:</p>
<pre name="code" class="php">
$params = array(
	'theme_location' =&gt; 'primary',
	'menu_id' =&gt; 'nav',
	'walker' =&gt; new description_walker()
);
wp_nav_menu($params);
</pre>
<h3>The Walker Class</h3>
<p>Now we&#8217;re ready to add those descriptions in using our Walker class:</p>
<pre name="code" class="php">
class description_walker extends Walker_Nav_Menu {
	function start_el(&#038;$output, $item, $depth, $args) {
		global $wp_query;
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

		$class_names = $value = '';

		$classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;

		$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
		$class_names = ' class="'. esc_attr( $class_names ) . '"';

		$output .= $indent . '&lt;li id="menu-item-'. $item-&gt;ID . '"' . $value . $class_names .'&gt;';

		$attributes  = ! empty( $item-&gt;attr_title ) ? ' title="'  . esc_attr( $item-&gt;attr_title ) .'"' : '';
		$attributes .= ! empty( $item-&gt;target )     ? ' target="' . esc_attr( $item-&gt;target     ) .'"' : '';
		$attributes .= ! empty( $item-&gt;xfn )        ? ' rel="'    . esc_attr( $item-&gt;xfn        ) .'"' : '';
		$attributes .= ! empty( $item-&gt;url )        ? ' href="'   . esc_attr( $item-&gt;url        ) .'"' : '';
		$description  = ! empty( $item-&gt;description ) ? '&lt;span&gt;'.esc_attr( $item-&gt;description ).'&lt;/span&gt;' : '';

		if($depth != 0) {
			$description = $append = $prepend = "";
		}

		$item_output = $args-&gt;before;
		$item_output .= '&lt;a'. $attributes .'&gt;';
		$item_output .= $args-&gt;link_before .apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );
		$item_output .= $description.$args-&gt;link_after;
		$item_output .= '&lt;/a&gt;';
		$item_output .= $args-&gt;after;

		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
	}
}
</pre>
<p>There is a lot going on here. For more information on Walker classes in general, let me refer you to another tutorial: <a href="http://wp.tutsplus.com/tutorials/creative-coding/understanding-the-walker-class/">Understanding the Walker Class</a>. The most important part you should understand here is that we&#8217;re rebuilding the output of each link item and adding in the description. On line 19 of the snippet above you can see where we get the item description if it exists and make it the value of <code>$description</code> wrapped in a span tag so that we can style the descriptions separately. Then in lines 24-29 where we piece the link item back together, we add in the description right before the close of the anchor tag so that it becomes part of the link itself.</p>
<p>Using the Twenty Eleven theme, you should now have something that looks like this:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/284_wp_nav_menu/wp_nav_menu3.jpg" width="564" height="118" /></div>
<h3>Style It Up</h3>
<p>Let&#8217;s add a bit of styling to make it more legible:</p>
<pre name="code" class="css">
#nav a {
	line-height: 20px;
	padding: 10px 15px;
}

#nav a span {
	display: block;
	font-size: 11px;
	color: #ccc;
}

#nav a:hover span {
	color: #999;
}
</pre>
<p>This will change the height and padding of each link, cause the description within the span tag to drop to its own line, and adjust the font sizes and colors a bit for a final result that looks like this:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/284_wp_nav_menu/wp_nav_menu4b.jpg" width="600" height="91" /></div>
<hr />
<h2>Relation Functions</h2>
<p>Not only can you use <code>wp_nav_menu()</code> to output your menu with all customizations, you can go a little further with some of its related functions.</p>
<h3><code>has_nav_menu()</code></h3>
<p>This function is great for only displaying a particular menu if that menu has been assigned to your theme location. For instance, you may want to create a top navigation on your theme for lesser navigation items that a user may not want in their main navigation. This could be things like a home link, &quot;Advertise With Us&quot;, or other lower calls to action. But as a theme distributor, if you don&#8217;t know if that&#8217;s going to be something the user wants to use, simply use a condition like so:</p>
<pre name="code" class="php">
if (has_nav_menu('top-menu')) {
	wp_nav_menu('theme_location='top-menu');
}
</pre>
<h3><code>wp_get_nav_menu_items()</code></h3>
<p>This function will return an array of items from a particular menu. This may be particular useful if you want to build a custom menu list without using a Walker Class. You lose a lot of functionality such as the menu item&#8217;s current class, but it&#8217;s a great way to loop through an array of menu items for a simple solution.</p>
<hr />
<h2>Conclusion</h2>
<p>There are a lot of things you can do to customize your navigation menus when you know more about the flexibility that is offered with built in parameters and being able to have greater control with the Walker Class. Need to add another span tag with the class of &quot;<code>icon</code>&quot; for custom icons to each item? No problem.</p>
<p>Being able to have full control over the placement and output of menus extends your capabilities as a theme developer an unmeasurable amount of possibilities. What are some of the things you can use that Walker class to do?</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/function-examination-wp_nav_menu/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Your Own Video Shortcode</title>
		<link>http://wp.tutsplus.com/articles/tips-articles/quick-tip-your-own-video-shortcode/</link>
		<comments>http://wp.tutsplus.com/articles/tips-articles/quick-tip-your-own-video-shortcode/#comments</comments>
		<pubDate>Sun, 27 May 2012 10:42:27 +0000</pubDate>
		<dc:creator>Barış Ünver</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[Shortcodes]]></category>
		<category><![CDATA[Video]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25516</guid>
		<description><![CDATA[<p>You probably use a video embedding plugin or you just use the embed codes of video sites. But there&#8217;s a third, easier way to embed videos in your WordPress site: a simple (but useful) video shortcode.<span id="more-25516"></span></p>
<hr />
<h2>Why Should I Use a Video Shortcode?</h2>
<ul>
<li>Because video embedding plugins are just another little burden for your blog. They take some space on your disk (granted, not more than 1MB), they always query your database for their options and you need to <em>learn</em> how to use the plugins.</li>
<li>Because embedding the codes of the video sites can be corrupted &ndash; especially when you switch between the WYSIWYG editor and the HTML editor.</li>
<li>And most importantly: Because shortcodes are awesome! They&#8217;re easy to use, they can have the functionality of many plugins and their code doesn&#8217;t break in your posts!</li>
</ul>
<hr />
<h2>Exploring the Video Sites</h2>
<p>We&#8217;re going to work with 7 video hosting sites:</p>
<ol>
<li>YouTube (obviously!)</li>
<li>Vimeo</li>
<li>Dailymotion</li>
<li>Yahoo! Screen</li>
<li>Blip.tv</li>
<li>Veoh</li>
<li>Viddler</li>
</ol>
<p>Let&#8217;s see what their embed codes look like:</p>
<h3>YouTube</h3>
<p>The default embed code looks like this:</p>
<pre name="code" class="html">
/* Original video: youtube.com/watch?v=dQw4w9WgXcQ */
&lt;iframe width=&quot;420&quot; height=&quot;315&quot; src=&quot;http://www.youtube.com/embed/dQw4w9WgXcQ&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;
</pre>
<p>But there&#8217;s one option, the &#8220;privacy-enhanced mode&#8221; which adds &#8220;-nocookie&#8221; to the domain and we&#8217;re going to use it in our shortcode.</p>
<h3>Vimeo</h3>
<pre name="code" class="html">
/* Original video: vimeo.com/36804448 */
&lt;iframe src=&quot;http://player.vimeo.com/video/36804448&quot; width=&quot;500&quot; height=&quot;281&quot; frameborder=&quot;0&quot; webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt;&lt;/iframe&gt;
</pre>
<p>Simple and elegant. That&#8217;s why people love Vimeo.</p>
<h3>Dailymotion</h3>
<pre name="code" class="html">
/* Original video: dailymotion.com/video/xhwpbg_bridgestone-15-sec-spot_auto */
&lt;iframe frameborder=&quot;0&quot; width=&quot;480&quot; height=&quot;360&quot; src=&quot;http://www.dailymotion.com/embed/video/xhwpbg&quot;&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;a href=&quot;http://www.dailymotion.com/video/xhwpbg_bridgestone-15-sec-spot_auto&quot; target=&quot;_blank&quot;&gt;BridgeStone 15 Sec spot&lt;/a&gt; &lt;i&gt;by &lt;a href=&quot;http://www.dailymotion.com/DailymotionUSA&quot; target=&quot;_blank&quot;&gt;DailymotionUSA&lt;/a&gt;&lt;/i&gt;
</pre>
<p>I think adding a link below the embed code is just <em>not cool</em>, so we&#8217;re not adding that to our shortcode.</p>
<h3>Yahoo! Screen</h3>
<pre name="code" class="html">
/* Original video: screen.yahoo.com/mysterious-death-of-500-fish-in-german-lake-blamed-on-urinating-swimmers-29322943.html */
&lt;div&gt;&lt;iframe frameborder=&quot;0&quot; width=&quot;576&quot; height=&quot;324&quot; src=&quot;http://d.yimg.com/nl/vyc/site/player.html#shareUrl=http%3A%2F%2Fscreen.yahoo.com%2Fmysterious-death-of-500-fish-in-german-lake-blamed-on-urinating-swimmers-29322943.html&amp;vid=29322943&amp;browseCarouselUI=hide&amp;repeat=0&amp;startScreenCarouselUI=hide&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;
</pre>
<p>The embed code is a little weird on Yahoo! Screen but I found a way to shorten it which will be easier to use in our shortcode.</p>
<h3>Blip.tv</h3>
<pre name="code" class="html">
/* Original video: blip.tv/mister-glasses/episode-7-5600357 */
&lt;iframe src=&quot;http://blip.tv/play/AYLV6UkC.html?p=1&quot; width=&quot;780&quot; height=&quot;438&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;&lt;embed type=&quot;application/x-shockwave-flash&quot; src=&quot;http://a.blip.tv/api.swf#AYLV6UkC&quot; style=&quot;display:none&quot;&gt;&lt;/embed&gt;
</pre>
<p>This is a hard one &ndash; this doesn&#8217;t have the video ID (from the video&#8217;s URL) in the embed code. But thanks to some research, I figured out how to use the ID! :)</p>
<h3>Veoh</h3>
<pre name="code" class="html">
/* Original video: veoh.com/watch/v27458670er62wkCt */
&lt;object width=&quot;410&quot; height=&quot;341&quot; id=&quot;veohFlashPlayer&quot; name=&quot;veohFlashPlayer&quot;&gt;&lt;param name=&quot;movie&quot; value=&quot;http://www.veoh.com/swf/webplayer/WebPlayer.swf?version=AFrontend.5.7.0.1355&amp;permalinkId=v27458670er62wkCt&amp;player=videodetailsembedded&amp;videoAutoPlay=0&amp;id=anonymous&quot;&gt;&lt;/param&gt;&lt;param name=&quot;allowFullScreen&quot; value=&quot;true&quot;&gt;&lt;/param&gt;&lt;param name=&quot;allowscriptaccess&quot; value=&quot;always&quot;&gt;&lt;/param&gt;&lt;embed src=&quot;http://www.veoh.com/swf/webplayer/WebPlayer.swf?version=AFrontend.5.7.0.1355&amp;permalinkId=v27458670er62wkCt&amp;player=videodetailsembedded&amp;videoAutoPlay=0&amp;id=anonymous&quot; type=&quot;application/x-shockwave-flash&quot; allowscriptaccess=&quot;always&quot; allowfullscreen=&quot;true&quot; width=&quot;410&quot; height=&quot;341&quot; id=&quot;veohFlashPlayerEmbed&quot; name=&quot;veohFlashPlayerEmbed&quot;&gt;&lt;/embed&gt;&lt;/object&gt;&lt;br /&gt;&lt;font size=&quot;1&quot;&gt;Watch &lt;a href=&quot;http://www.veoh.com/watch/v27458670er62wkCt&quot;&gt;Intense Cat&lt;/a&gt; in &lt;a href=&quot;http://www.veoh.com/browse/videos/category/animals&quot;&gt;Animals&lt;/a&gt;&amp;nbsp;&amp;nbsp;|&amp;nbsp;&amp;nbsp;View More &lt;a href=&quot;http://www.veoh.com&quot;&gt;Free Videos Online at Veoh.com&lt;/a&gt;&lt;/font&gt;
</pre>
<p>Ah, the &lt;object&gt; tag&#8230; Don&#8217;t worry, we&#8217;re not going to use it!</p>
<h3>Viddler</h3>
<pre name="code" class="html">
/* Original video: viddler.com/v/978c9ba2 */
&lt;iframe id=&quot;viddler-978c9ba2&quot; src=&quot;//www.viddler.com/embed/978c9ba2/?f=1&amp;autoplay=0&amp;player=full&amp;loop=false&amp;nologo=false&amp;hd=false&quot; width=&quot;437&quot; height=&quot;315&quot; frameborder=&quot;0&quot; mozallowfullscreen=&quot;true&quot; webkitallowfullscreen=&quot;true&quot;&gt;&lt;/iframe&gt;
</pre>
<p>That&#8217;s all. Now, let&#8217;s get to the fun part!</p>
<hr />
<h2>The Shortcode: <code>[vid]</code></h2>
<p>We&#8217;ll create 4 attributes for this shortcode &ndash; the name of the site, the ID of the video and the width and the height of the video. You can set some default values for the attributes:</p>
<pre name="code" class="php">
function vid_sc($atts, $content=null) {
	extract(
		shortcode_atts(array(
			'site' =&gt; 'youtube',
			'id' =&gt; '',
			'w' =&gt; '400',
			'h' =&gt; '250'
		), $atts)
	);
}
add_shortcode('vid','vid_sc');
</pre>
<p>Then comes the part where the function generates the <code>$src</code> variable which generates the <code>src</code> attribute for the <code>iframe</code>:</p>
<pre name="code" class="php">
// YouTube with "privacy-enhanced mode":
if ( $site == &quot;youtube&quot; ) {
	$src = 'http://www.youtube-nocookie.com/embed/'.$id;
}
// Vimeo:
else if ( $site == &quot;vimeo&quot; ) {
	$src = 'http://player.vimeo.com/video/'.$id;
}
// Dailymotion:
else if ( $site == &quot;dailymotion&quot; ) {
	$src = 'http://www.dailymotion.com/embed/video/'.$id;
}
// Yahoo! Screen with some cuts in the URI:
else if ( $site == &quot;yahoo&quot; ) {
	$src = 'http://d.yimg.com/nl/vyc/site/player.html#vid='.$id;
}
// Blip.tv with some "hacks" in the URI:
else if ( $site == &quot;bliptv&quot; ) {
	$src = 'http://a.blip.tv/scripts/shoggplayer.html#file=http://blip.tv/rss/flash/'.$id;
}
// The Veoh URI has some hacks, too:
else if ( $site == &quot;veoh&quot; ) {
	$src = 'http://www.veoh.com/static/swf/veoh/SPL.swf?videoAutoPlay=0&amp;permalinkId='.$id;
}
// Viddler:
else if ( $site == &quot;viddler&quot; ) {
	$src = 'http://www.viddler.com/simple/'.$id;
}
</pre>
<p>And of course, we <em>return</em> the output. Here&#8217;s the full code of our brand new video shortcode:</p>
<pre name="code" class="php">
function vid_sc($atts, $content=null) {
	extract(
		shortcode_atts(array(
			'site' =&gt; 'youtube',
			'id' =&gt; '',
			'w' =&gt; '600',
			'h' =&gt; '370'
		), $atts)
	);
	if ( $site == &quot;youtube&quot; ) { $src = 'http://www.youtube-nocookie.com/embed/'.$id; }
	else if ( $site == &quot;vimeo&quot; ) { $src = 'http://player.vimeo.com/video/'.$id; }
	else if ( $site == &quot;dailymotion&quot; ) { $src = 'http://www.dailymotion.com/embed/video/'.$id; }
	else if ( $site == &quot;yahoo&quot; ) { $src = 'http://d.yimg.com/nl/vyc/site/player.html#vid='.$id; }
	else if ( $site == &quot;bliptv&quot; ) { $src = 'http://a.blip.tv/scripts/shoggplayer.html#file=http://blip.tv/rss/flash/'.$id; }
	else if ( $site == &quot;veoh&quot; ) { $src = 'http://www.veoh.com/static/swf/veoh/SPL.swf?videoAutoPlay=0&amp;permalinkId='.$id; }
	else if ( $site == &quot;viddler&quot; ) { $src = 'http://www.viddler.com/simple/'.$id; }
	if ( $id != '' ) {
		return '&lt;iframe width=&quot;'.$w.'&quot; height=&quot;'.$h.'&quot; src=&quot;'.$src.'&quot; class=&quot;vid iframe-'.$site.'&quot;&gt;&lt;/iframe&gt;';
	}
}
add_shortcode('vid','vid_sc');
</pre>
<blockquote>
<p>Tip within the quick tip: Take note that the <code>iframe</code> has two CSS classes: <code>vid</code> and <code>iframe-$site</code> (e.g. <code>iframe-youtube</code>). You should add <code>vid {border:0;}</code> to your CSS file since we didn&#8217;t define the <code>frameborder</code> attribute in our <code>iframe</code> tag.</p>
</blockquote>
<hr />
<h2>Usage Examples</h2>
<p>The default usage is simple enough:</p>
<p><code>[vid site="youtube" id="dQw4w9WgXcQ" w="600" h="340"]</code></p>
<p>But to make it even <em>simpler</em>, we set default values for <code>site</code>, <code>w</code> and <code>h</code>. So, if you want to embed a YouTube video, you can just use it like this:</p>
<p><code>[vid id="dQw4w9WgXcQ"]</code></p>
<p>You should change the width and the height to match your blog. Also, if you use Vimeo more than YouTube, you can change the default <code>site</code> value to &#8220;vimeo&#8221;.</p>
<p>That&#8217;s it! Add this to your <strong>functions.php</strong> file and you can start using the shortcode. Enjoy!</p>
<p><em>Update: We&#8217;ve added a usage example section to the article now to make things clearer.</em></p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/articles/tips-articles/quick-tip-your-own-video-shortcode/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Writing Custom Queries in WordPress</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/writing-custom-queries-in-wordpress/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/writing-custom-queries-in-wordpress/#comments</comments>
		<pubDate>Sat, 26 May 2012 11:38:40 +0000</pubDate>
		<dc:creator>Adam Burucs</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[custom queries]]></category>
		<category><![CDATA[wpdb]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25510</guid>
		<description><![CDATA[<p>With custom queries you can make any data reading and/or manipulation you want. Instantly a world of new possibilities open up.<span id="more-25510"></span></p>
<hr />
<h2>Why Use Custom Queries?</h2>
<p>The basic functionalities in WordPress are fine for most simple needs, but what would you do if you want to implement some specific needs? Are you writing a plugin maybe? Then you should learn how you can use SQL queries in WordPress right now! The official references can be found in the WordPress Codex (<a href="http://codex.wordpress.org/Custom_Queries">Custom Queries</a> and the <a href="http://codex.wordpress.org/Class_Reference/wpdb">WPDB class</a>).</p>
<hr />
<h2>The <code>wpdb</code> Class</h2>
<p>This global WordPress class is key for using queries. In fact, every function uses this class.</p>
<hr />
<h2>Using <code>query</code></h2>
<p>The query function needs a string containing the custom query. The returning value is an integer corresponding to the number of rows affected/selected, and false when there is an error.</p>
<pre name="code" class="php">
$query = "SELECT COUNT(apple) FROM fruits";
$wpdb-&gt;query($query);
</pre>
<hr />
<h2><code>get_results</code></h2>
<p>This function gets multiple rows when executing a query. By default the result of the function is an array.</p>
<pre name="code" class="php">
$query = "
	SELECT *
	FROM wp_terms wt
	INNER JOIN wp_term_taxonomy wtt ON wt.term_id = wtt.term_id
	WHERE wtt.taxonomy = 'post_tag' AND wtt.count = 0";

$wpdb-&gt;get_results($query);
</pre>
<hr />
<h2><code>get_var</code></h2>
<p>This will return one variable from the database, but the complete result of the query is cached for later use. Returns NULL if no result is found.</p>
<pre name="code" class="php">
$query = "SELECT COUNT(*) FROM users";
$wpdb-&gt;get_var($query);
</pre>
<hr />
<h2><code>get_row</code></h2>
<p>A complete row will be returned as a result of the function, which can be an object, an associative array, or a numerically indexed array. NULL is the result when no matching data is found. <code>result_type</code> can be <code>OBJECT</code>, <code>ARRAY_A</code> or <code>ARRAY_N</code> (object, associative array or numbered array). Offset is an integer with a default of 0.</p>
<pre name="code" class="php">
$query = "
SELECT * FROM wp_posts
WHERE post_type = 'post'";

$wpdb-&gt;get_row($query, ARRAY_A, 3);
</pre>
<hr />
<h2><code>get_col</code></h2>
<p>For getting a column, use this function. Output will be a dimensional array. An empty array will be returned if no result is found. The second parameter is the column offset.</p>
<pre name="code" class="php">
$query = "
SELECT * FROM wp_posts
WHERE post_type = 'post'";

$wpdb-&gt;get_col($query, 3);
</pre>
<hr />
<h2>Prepared Queries</h2>
<p>According to the php.net manual:</p>
<blockquote><p>&#8220;They [prepared queries] can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters.&#8221;</p>
</blockquote>
<p>You can protect SQL queries against SQL injection attacks. In short data in queries must be SQL-escaped before the query is executed to prevent injection attacks. This can be easily done with the prepare method. In the following example, the values &#8217;10&#8242;, &#8216;monkey&#8217; and &#8216;apple&#8217; will be escaped when used in this method.</p>
<pre name="code" class="php">
// Usage: $wpdb-&gt;prepare( 'query' [, value_parameter, value_parameter ... ] );

$wpdb-&gt;query( $wpdb-&gt;prepare(
	"INSERT INTO test_table (post_id, animal, food) VALUES ( %d, %s, %s )",
	array(
		10,
		'monkey',
		'apple'
	)
));
</pre>
<hr />
<h2>Setting Error Messages</h2>
<p>You can turn error messages on and off with the <code>show_errors</code> and <code>hide_errors</code> functions, but you can also print:</p>
<pre name="code" class="php">
$wpdb-&gt;show_errors();
$wpdb-&gt;hide_errors();
</pre>
<hr />
<h2>Cache Control</h2>
<p>Deleting the cache can be made with the <code>flush</code> function.</p>
<pre name="code" class="php">
$wpdb-&gt;flush();
</pre>
<hr />
<h2>Inserting Data</h2>
<pre name="code" class="php">
$wpdb-&gt;insert($table, $data, $format);

$wpdb-&gt;insert(
	'foods',
	array(
		'fruit' =&gt; 'apple',
		'year' =&gt; 2012
	),
	array(
		'%s',
		'%d'
	)
);
</pre>
<p>The used parameters in order are:</p>
<ul>
<li>the name of the table to insert data into</li>
<li>the data to insert (column =&gt; value pairs) without escaping</li>
<li>an array of formats to be mapped to each of the values in <code>$data</code>. If not present, all values will be treated as strings</li>
</ul>
<hr />
<h2>Updating Data</h2>
<pre name="code" class="php">
$wpdb-&gt;update(
	'foods',
	array(
		'fruit' =&gt; 'apple',	// string
		'year' =&gt;  'value2'	// integer (number)
	),
	array( 'ID' =&gt; 1 ),
	array(
		'%s',	// value1
		'%d'	// value2
	),
	array( '%d' )
);
</pre>
<p>The used parameters in order are:</p>
<ul>
<li>table name</li>
<li>data</li>
<li>where conditions</li>
<li>format</li>
<li>where_format</li>
</ul>
<hr />
<h2>Column Information</h2>
<p>You can get information about the columns of the most recent result with this function. When a function has returned an <code>OBJECT</code> and there are properties you don&#8217;t know much about, this can be useful.</p>
<pre name="code" class="php">
$wpdb-&gt;get_col_info('type', offset);
</pre>
<ul>
<li>Type: the information you want to retrieve, some examples are here
<ul>
<li><code>name</code> &ndash; column name (this is the default)</li>
<li><code>table</code> &ndash; name of the table the column belongs to</li>
<li><code>max_length</code> &ndash; maximum length of the column</li>
<li><code>not_null</code> &ndash; 1 if the column cannot be NULL</li>
<li>more can be found in the WordPress Codex <a href="http://codex.wordpress.org/Class_Reference/wpdb">WPDB reference</a></li>
</ul>
</li>
<li>Offset: specify the column from which to retrieve information (0 is the first column)</li>
</ul>
<hr />
<h2>Referencing WordPress Tables</h2>
<p>WordPress database tables can be referenced in the <code>wpdb</code> class. This is very convenient as table names can be different than the default ones. Here&#8217;s a list of WordPress database table references:</p>
<ul>
<li><code>$wpdb-&gt;posts;</code></li>
<li><code>$wpdb-&gt;postmeta;</code></li>
<li><code>$wpdb-&gt;comments;</code></li>
<li><code>$wpdb-&gt;commentmeta;</code></li>
<li><code>$wpdb-&gt;terms;</code></li>
<li><code>$wpdb-&gt;term_taxonomy;</code></li>
<li><code>$wpdb-&gt;term_relationships;</code></li>
<li><code>$wpdb-&gt;users;</code></li>
<li><code>$wpdb-&gt;usermeta;</code></li>
<li><code>$wpdb-&gt;links;</code></li>
<li><code>$wpdb-&gt;options;</code></li>
</ul>
<p>Note that we don&#8217;t need to include the prefix, that&#8217;s the benefit here where the <code>wpdb</code> class takes care of that for us.</p>
<p>There we have it! A reference for custom queries in WordPress, all in one place for you.</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/writing-custom-queries-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Facebook Like Box Widget for WordPress</title>
		<link>http://wp.tutsplus.com/tutorials/widgets/facebook-like-box-widget-for-wordpress/</link>
		<comments>http://wp.tutsplus.com/tutorials/widgets/facebook-like-box-widget-for-wordpress/#comments</comments>
		<pubDate>Fri, 25 May 2012 10:41:15 +0000</pubDate>
		<dc:creator>Paul Underwood</dc:creator>
				<category><![CDATA[Widgets]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[plugin development]]></category>
		<category><![CDATA[widgets]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25494</guid>
		<description><![CDATA[<p>If your website has a Facebook page then it&#8217;s a good idea to promote this to your readers by displaying a Facebook like box on the sidebar of the blog.</p>
<p>In this tutorial we are going to create a <a href="http://codex.wordpress.org/WordPress_Widgets" title="WordPress Widget">WordPress widget</a> which displays your Facebook like box. With this WordPress widget you will have the option to display the box header, show your latest fans and show your latest Facebook stream.<span id="more-25494"></span></p>
<hr />
<h2>Facebook Pages</h2>
<p>Facebook Pages have been around for a while now and they have recently been converted to use the new timeline feature to bring even more exposure to your previous posts on your profile.</p>
<p>A Facebook Page is the same as a personal page but you can not friend other people, this is because Facebook Pages are for businesses to connect with their customers.</p>
<p>Facebook Pages give you a more dynamic relationship with the public figures and organizations you are interested in.</p>
<p>If you have your own business you too can <a href="https://www.facebook.com/pages/create.php">create your own Facebook Page</a>.</p>
<hr />
<h2>Facebook Like Box</h2>
<p>A Facebook like box is a social plugin which enables Facebook Page owners to display a like button and a status stream on their own website.</p>
<p>The like box means visitors to your site can:</p>
<ul>
<li>See how many people like the page and which of their friends already like this page.</li>
<li>View your recent status updates.</li>
<li>Like your Facebook Page without leaving your site.</li>
</ul>
<p>Here is an example of Wptuts+&#8217;s Facebook like box.</p>
<div id="fb-root"></div>
<p><script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script></p>
<div class="fb-like-box" data-href="http://www.facebook.com/wptutsplus" data-width="292" data-show-faces="true" data-stream="true" data-header="true"></div>
<p>To create a Facebook Like Box for your Facebook page you need to register a Facebook app to be able to use the <a href="https://developers.facebook.com/docs/opengraph/" title="Open Graph API">Facebook open graph API</a>.</p>
<p>Now you see what the Facebook like box is we can understand how to turn this into a WordPress widget.</p>
<hr />
<h2>WordPress Widgets</h2>
<p>Before we start coding the widget we need to understand what a WordPress widget is and how we can use the <a href="http://codex.wordpress.org/Widgets_API" title="WordPress Widget API" target="_blank">WordPress Widget API</a> to easily create WordPress widgets.</p>
<p>A WordPress widget is a piece of PHP code which will run inside a WordPress sidebar.</p>
<p>A WordPress sidebar is a registered area in your theme where you can add WordPress widgets.</p>
<p>WordPress widgets can easily be added to sidebars by going to the Widget page in the Dashboard and navigate to <strong>Appearance -&gt; Widgets</strong>. From this Widgets page you are able to drag and drop widgets into a sidebar of your choice. The widget should have some sort of Admin form so you can edit the data shown by the widget.</p>
<hr />
<h2>WordPress <code>WP_Widget</code></h2>
<p>To create a WordPress widget all you need to do is inherit from the standard <code>WP_Widget</code> class and use some of its functions.</p>
<p>There are three main functions that need to be used for the widget to work these functions are <code>form()</code>, <code>widget()</code> and <code>update()</code>.</p>
<p>The <code>WP_Widget</code> class is located in <strong>wp-includes/widgets.php</strong>.</p>
<hr />
<h2>WordPress Starter Widget</h2>
<p>Below is the boilerplate of a <a href="http://codex.wordpress.org/Widgets_API" title="WordPress Widget">WordPress widget</a>, when you create a new widget just copy and paste the below code as a starting point for your widget.</p>
<pre name="code" class="php">
/**
 * Adds Foo_Widget widget.
 */
class Foo_Widget extends WP_Widget {

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {
		parent::__construct(
			'foo_widget', // Base ID
			'Foo_Widget', // Name
			array( 'description' =&gt; __( 'A Foo Widget', 'text_domain' ), ) // Args
		);
	}

	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );
		$title = apply_filters( 'widget_title', $instance['title'] );

		echo $before_widget;
		if ( ! empty( $title ) )
			echo $before_title . $title . $after_title;
		?&gt;Hello, World!&lt;?php
		echo $after_widget;
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = strip_tags( $new_instance['title'] );

		return $instance;
	}

	/**
	 * Back-end widget form.
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		if ( isset( $instance[ 'title' ] ) ) {
			$title = $instance[ 'title' ];
		}
		else {
			$title = __( 'New title', 'text_domain' );
		}
		?&gt;
		&lt;p&gt;
		&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;"&gt;&lt;?php _e( 'Title:' ); ?&gt;&lt;/label&gt;
		&lt;input class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;" type="text" value="&lt;?php echo esc_attr( $title ); ?&gt;" /&gt;
		&lt;/p&gt;
		&lt;?php
	}

} // class Foo_Widget
</pre>
<hr />
<h2>Creating Facebook Like Box Widget</h2>
<p>We are going to create a WordPress widget to allow you to easily add and change a Facebook like box on your WordPress blog.</p>
<p>The benefit of using a widget is for the flexibility it will give you. The choice that you have on your Facebook like box allows you to completely change the functionality just by placing different attributes on the like box.</p>
<p>The Facebook like box takes the following attributes:</p>
<ul>
<li><code>data-href</code> &ndash; The URL to your Facebook page.</li>
<li><code>data-width</code> &ndash; The width of the like box.</li>
<li><code>data-show-faces</code> &ndash; A true or false value which decides if you will show people who like your page.</li>
<li><code>data-stream</code> &ndash; A true or false value which decides if you will show your latest status updates.</li>
<li><code>data-header</code> &ndash; A true or false value which decides if you will show the find us on Facebook bar.</li>
</ul>
<p>These are the options which we need to make sure the user can change in the widget admin screen, so they can change the look of the like box directly in the WordPress dashboard.</p>
<p>Now we know what to expect from the Facebook like box we can start coding.</p>
<h3>Facebook Widget Constructor</h3>
<p>First we are going to register the widget on the <code>widget_init</code> action.</pre>
<pre name="code" class="php">
/*
 * Plugin Name: Paulund Facebook Like Box
 * Plugin URI: http://www.paulund.co.uk
 * Description: A widget that a facebook like box for your website
 * Version: 1.0
 * Author: Paul Underwood
 * Author URI: http://www.paulund.co.uk
 * License: GPL2

    Copyright 2012  Paul Underwood

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

/**
 * Register the Widget
 */
add_action( 'widgets_init', create_function( '', 'register_widget("pu_facebook_widget");' ) );
</pre>
<p>The <code>register_widget</code> function will call the <code>pu_facebook_widget</code> class. In the constructor we can create the widget by passing through arguments to the <code>WP_Widget</code> constructor.</p>
<pre name="code" class="php">
/**
 * Create the widget class and extend from the WP_Widget
 */
class pu_facebook_widget extends WP_Widget {

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {

		parent::__construct(
			'pu_facebook_widget',		// Base ID
			'Facebook Like Box',		// Name
			array(
				'classname'		=&gt;	'pu_facebook_widget',
				'description'	=&gt;	__('A widget that displays a facebook like box from your facebook page.', 'framework')
			)
		);

	} // end constructor
}
</pre>
<h3>Widget Function</h3>
<p>The widget function is called to output the widget in the sidebar. This is where we need to collect the data input from the user on the dashboard and display the widget on the website.</p>
<p>Use the following function to display your Facebook like box.</p>
<pre name="code" class="php">
	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );

		/* Our variables from the widget settings. */
		$this-&gt;widget_title = apply_filters('widget_title', $instance['title'] );

		$this-&gt;facebook_id = $instance['app_id'];
		$this-&gt;facebook_username = $instance['page_name'];
		$this-&gt;facebook_width = $instance['width'];
		$this-&gt;facebook_show_faces = ($instance['show_faces'] == "1" ? "true" : "false");
		$this-&gt;facebook_stream = ($instance['show_stream'] == "1" ? "true" : "false");
		$this-&gt;facebook_header = ($instance['show_header'] == "1" ? "true" : "false");

		add_action('wp_footer', array(&#038;$this,'add_js'));

		/* Display the widget title if one was input (before and after defined by themes). */
		if ( $this-&gt;widget_title )
			echo $this-&gt;widget_title;

		/* Like Box */
		?&gt;
			&lt;div class="fb-like-box"
				data-href="http://www.facebook.com/&lt;?php echo $this-&gt;facebook_username; ?&gt;"
				data-width="&lt;?php echo $this-&gt;facebook_width; ?&gt;"
				data-show-faces="&lt;?php echo $this-&gt;facebook_show_faces; ?&gt;"
				data-stream="&lt;?php echo $this-&gt;facebook_stream; ?&gt;"
				data-header="&lt;?php echo $this-&gt;facebook_header; ?&gt;"&gt;&lt;/div&gt;
		&lt;?php
	}
</pre>
<p>You may have noticed we add an action to the <code>wp_footer</code> to run the function <code>add_js</code>. This is where you will need to add the Facebook JavaScript to get the like box to work correctly.</p>
<pre name="code" class="php">
/**
 * Add Facebook javascripts
 */
public function add_js() {
	echo '&lt;div id="fb-root"&gt;&lt;/div&gt;
		&lt;script&gt;(function(d, s, id) {
			var js, fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id)) return;
			js = d.createElement(s); js.id = id;
			js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&#038;appId='.$this-&gt;facebook_id.'";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, \'script\', \'facebook-jssdk\'));&lt;/script&gt;';
}
</pre>
<h3>Update Function</h3>
<p>The update function is used to update the WordPress database when the widget admin form is submitted.</p>
<p>This is where you will need to place any validation needed on the values from the form. This takes 2 parameters, an array of values sent to be saved and an array of values which are currently stored. The return of this function will be the new values stored in the database.</p>
<pre name="code" class="php">
/**
 * Sanitize widget form values as they are saved.
 *
 * @see WP_Widget::update()
 *
 * @param array $new_instance Values just sent to be saved.
 * @param array $old_instance Previously saved values from database.
 *
 * @return array Updated safe values to be saved.
 */
function update( $new_instance, $old_instance ) {
	$instance = $old_instance;

	/* Strip tags for title and name to remove HTML (important for text inputs). */
	$instance['title'] = strip_tags( $new_instance['title'] );
	$instance['app_id'] = strip_tags( $new_instance['app_id'] );
	$instance['page_name'] = strip_tags( $new_instance['page_name'] );
	$instance['width'] = strip_tags( $new_instance['width'] );

	$instance['show_faces'] = (bool)$new_instance['show_faces'];
	$instance['show_stream'] = (bool)$new_instance['show_stream'];
	$instance['show_header'] = (bool)$new_instance['show_header'];

	return $instance;
}
</pre>
<h3>Form Function</h3>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/281_Facebook_Like_Box_Widget_for_WordPress/facebook_like_box.png" alt="facebook_like_box" title="facebook_like_box" width="264" height="438" /></div>
<p>The form function is used to create the form on the widget dashboard. This will need to be pre-populated with the current values in the database and make it easy for the user to change the values to change the widget behaviour.</p>
<pre name="code" class="php">
/**
 * Create the form for the Widget admin
 *
 * @see WP_Widget::form()
 *
 * @param array $instance Previously saved values from database.
 */
function form( $instance ) {

	/* Set up some default widget settings. */
	$defaults = array(
		'title' =&gt; $this-&gt;widget_title,
		'app_id' =&gt; $this-&gt;facebook_id,
		'page_name' =&gt; $this-&gt;facebook_username,
		'width' =&gt; $this-&gt;facebook_width,
		'show_faces' =&gt; $this-&gt;facebook_show_faces,
		'show_stream' =&gt; $this-&gt;facebook_stream,
		'show_header' =&gt; $this-&gt;facebook_header
	);

	$instance = wp_parse_args( (array) $instance, $defaults ); ?&gt;

	&lt;!-- Widget Title: Text Input --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;"&gt;&lt;?php _e('Title:', 'framework') ?&gt;&lt;/label&gt;
	&lt;input type="text" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;" value="&lt;?php echo $instance['title']; ?&gt;" /&gt;&lt;/p&gt;

	&lt;!-- App id: Text Input --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'app_id' ); ?&gt;"&gt;&lt;?php _e('App Id', 'framework') ?&gt;&lt;/label&gt;
	&lt;input type="text" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'app_id' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'app_id' ); ?&gt;" value="&lt;?php echo $instance['app_id']; ?&gt;" /&gt;&lt;/p&gt;

	&lt;!-- Page name: Text Input --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'page_name' ); ?&gt;"&gt;&lt;?php _e('Page name (http://www.facebook.com/[page_name])', 'framework') ?&gt;&lt;/label&gt;
	&lt;input type="text" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'page_name' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'page_name' ); ?&gt;" value="&lt;?php echo $instance['page_name']; ?&gt;" /&gt;&lt;/p&gt;

	&lt;!-- Width: Text Input --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'width' ); ?&gt;"&gt;&lt;?php _e('Width', 'framework') ?&gt;&lt;/label&gt;
	&lt;input type="text" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'width' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'width' ); ?&gt;" value="&lt;?php echo $instance['width']; ?&gt;" /&gt;&lt;/p&gt;

	&lt;!-- Show Faces: Checkbox --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'show_faces' ); ?&gt;"&gt;&lt;?php _e('Show Faces', 'framework') ?&gt;&lt;/label&gt;
	&lt;input type="checkbox" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'show_faces' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'show_faces' ); ?&gt;" value="1" &lt;?php echo ($instance['show_faces'] == "true" ? "checked='checked'" : ""); ?&gt; /&gt;&lt;/p&gt;

	&lt;!-- Show Stream: Checkbox --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'show_stream' ); ?&gt;"&gt;&lt;?php _e('Show Stream', 'framework') ?&gt;&lt;/label&gt;&lt;input type="checkbox" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'show_stream' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'show_stream' ); ?&gt;" value="1" &lt;?php echo ($instance['show_stream'] == "true" ? "checked='checked'" : ""); ?&gt; /&gt;&lt;/p&gt;

	&lt;!-- Show Header: Checkbox --&gt;
	&lt;p&gt;&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'show_header' ); ?&gt;"&gt;&lt;?php _e('Show Header', 'framework') ?&gt;&lt;/label&gt;
	&lt;input type="checkbox" class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'show_header' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'show_header' ); ?&gt;" value="1" &lt;?php echo ($instance['show_header'] == "true" ? "checked='checked'" : ""); ?&gt; /&gt;&lt;/p&gt;

	&lt;?php
}
</pre>
<p>You do not need to add a submit button as WordPress will automatically add it for you.</p>
<hr />
<h2>Download</h2>
<p>That's all you need to create a WordPress plugin which creates a widget to display your Facebook like page. All you have to do now is install the plugin, activate it, add the widget to a sidebar and fill out the form with your page details.</p>
<p>You can download this plugin from WordPress.org: <a href="http://wordpress.org/extend/plugins/facebook-like-box-paulund/">Download Facebook Like Box Plugin</a></p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/widgets/facebook-like-box-widget-for-wordpress/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>The Rewrite API: Post Types &amp; Taxonomies</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-post-types-taxonomies/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-post-types-taxonomies/#comments</comments>
		<pubDate>Thu, 24 May 2012 10:14:00 +0000</pubDate>
		<dc:creator>Stephen Harris</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Rewrite]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25488</guid>
		<description><![CDATA[<div class="seriesmeta">This entry is part 2 of 2 in the series <a href="http://wp.tutsplus.com/series/the-rewrite-api/" class="series-848" title="The Rewrite API">The Rewrite API</a></div><p>This is part two of a series looking at WordPress&#8217; Rewrite API. In part one we took a whistle stop tour of the basics of WordPress&#8217; Rewrite API. In this tutorial we will look at the rewrite settings available to us when registering a post type or taxonomy. While custom post types and taxonomies (unlike the default posts, categories and tags) don&#8217;t benefit from any Settings -&gt; Permalink interface, setting up rewrites for custom types is still fairly straightforward. We&#8217;ll also be using the methods introduced in part one, so if you haven&#8217;t already I recommend you read WordPress&#8217; <a href="http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/">Rewrite API Part One: The Basics</a>.<span id="more-25488"></span></p>
<hr />
<h2>Flushing the Rewrite Rules</h2>
<p>When you register a custom type, WordPress also registers rewrite rules (actually, <em>not quite</em>, and I&#8217;ll explain why in the &#8216;Permastructures&#8217; section). As mentioned in part one, these rules will only be included once the rewrite rules are &#8216;flushed&#8217;. Themes and plug-ins can force this &#8216;flushing&#8217; by calling <a href="http://codex.wordpress.org/Function_Reference/flush_rewrite_rules"><code>flush_rewrite_rules()</code></a>. This needs to, and should only, be done once on activation and then again on deactivation (to clean up after yourself).</p>
<p>Obviously, prior to flushing the rewrite rules, you need to have added them. However the <code>init</code> hook on which post types should be registered, has already been fired and when it was, your plug-in or theme wasn&#8217;t yet active and so your post types and taxonomies are not yet registered. In order to register the rewrite rules that come with your post types and taxonomies, this means you need to &#8216;manually&#8217; register them on activation, prior to flushing the rewrite rules. So, this should be your set up:</p>
<pre name="code" class="php">
function wptuts_register_types() {
	//function which registers your custom post type and taxonomies
}
add_action('init','wptuts_register_types');

function wptuts_plugin_activation() {

	// Register types to register the rewrite rules
	wptuts_register_types();

	// Then flush them
	flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'wptuts_plugin_activation');

function wptuts_plugin_deactivation() {

	flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'wptuts_plugin_activation');
</pre>
<p>Themes can use the hooks <code>after_switch_theme</code> for activation and <code>switch_theme</code> for de-activation.</p>
<hr />
<h2>Custom Post Types</h2>
<p>When you register a post type with <a href="http://codex.wordpress.org/Function_Reference/register_post_type"><code>register_post_type</code></a> one of the arguments available to you is the rewrite argument. This should be an array with the following keys:</p>
<ul>
<li><code>slug</code> &ndash; a slug used to identify the post type in URLs. The post&#8217;s slug is appended to this for the post&#8217;s permalink e.g. <code>www.example.com/<strong>books</strong>/the-wizard-of-oz</code></li>
<li><code>with_front</code> &ndash; true or false. If your post&#8217;s permalink structure begins with a constant base, such as &#8216;/blog&#8217; &ndash; this can also be added to your custom post type&#8217;s permalink structure by setting it to true e.g. true will give <code>www.example.com/blog/books/</code> and false <code>www.example.com/books/</code></li>
<li><code>feeds</code> &ndash; true or false. Whether to generate feed rewrite rules e.g. <code>www.example.com/books/feed/rss</code> and <code>www.example.com/book/rss</code>. The default value is the value of <code>has_archive</code>.</li>
<li><code>pages</code> &ndash; true or false. Whether to generate rule for &#8216;pretty&#8217; pagination for the post type archive e.g. <code>www.example.com/books/page/2</code> instead of <code>www.example.com/books?page=2</code>. Defaults to true.</li>
<li><code>ep_mask</code> &ndash; This used to be a separate argument: <code>permalink_epmask</code>. As of 3.4 it will move to the rewrite array. The default is <code>EP_PERMALINK</code>.</li>
</ul>
<p>The &#8216;feeds&#8217; and &#8216;pages&#8217; keys concern only the post-type archive page (for which you need to have set the <code>has_archive</code> argument to true). From this rewrite array WordPress handles the generation of the rewrite rules for your post types automatically. As an example:</p>
<pre name="code" class="php">
$labels = array(
	'name' =&gt; __('Books', 'your-plugins-translation-domain'),
	//array of labels
);

$args = array(
	'labels' =&gt; $labels,
	'has_archive'=&gt;true,
	'rewrite' =&gt; array(
		'slug'=&gt;'books',
		'with_front'=&gt; false,
		'feed'=&gt; true,
		'pages'=&gt; true
	)
);
register_post_type('book',$args);
</pre>
<p>Would give the following rewrite rules:</p>
<ul>
<li>The permalink of the book &#8216;<code>the-wizard-of-oz</code>&#8216;: <code>www.example.com/books/the-wizard-of-oz</code></li>
<li>Archive of all books <code>www.example.com/books</code> (and <code>www.example.com/books/page/2</code>)</li>
<li>The feed of the above archive: <code>www.example.com/books/feed/rss</code> (and <code>www.example.com/books/rss</code>)</li>
</ul>
<hr />
<h2>Taxonomies</h2>
<p>The <a href="http://codex.wordpress.org/Function_Reference/register_taxonomy"><code>register_taxonomy()</code></a> function offers fewer options:</p>
<ul>
<li><code>slug</code> &ndash; a slug to identify the taxonomy e.g. <code>www.example.com/<strong>genre</strong>/history</code></li>
<li><code>with_front</code> &ndash; As above.</li>
<li><code>hierarchical</code> &ndash; true or false. If set to true and the taxonomy is hierarchical, the term permalink reflects the hierarchy. Defaults to false.</li>
<li><code>ep_mask</code> &ndash; Added in 3.4. See EP Mask section below.</li>
</ul>
<p>The first two options are similar to the above. The hierarchical option gives the term permalinks the same structure as pages. For example, let &#8216;History&#8217; be a genre and &#8216;Military History&#8217; a sub-genre. With hierarchical set to false, &#8216;Military History&#8217; will have a the permalink:</p>
<pre name="code" class="php">
www.example.com/genre/military-history
</pre>
<p>Whereas, set to true, it will have:</p>
<pre name="code" class="php">
www.example.com/genre/military/military-history
</pre>
<p>Registering a taxonomy automatically registers your taxonomy-terms&#8217; feeds:</p>
<pre name="code" class="php">
www.example.com/genre/military-history/feed
</pre>
<blockquote><p>You can get the feed-link permalink to any taxonomy term with <code>$feed_link = get_term_feed_link($term_id, $taxonomy, $feed)</code></p>
</blockquote>
<hr />
<h2>Post Type Archives</h2>
<p>By default, WordPress doesn&#8217;t produce &#8216;pretty&#8217; permalinks for your custom post type&#8217;s year, month or day archives (nor the author archive &ndash; but we&#8217;ll leave that one for now). While:</p>
<pre name="code" class="php">
www.example.com/?post_type=book&amp;year=2012&amp;monthnum=05
</pre>
<p>Correctly gives an archive of all books published in May 2012:</p>
<pre name="code" class="php">
www.example.com/books/2012/05
</pre>
<p>Will give a 404 error. However, we can simply add extra rewrite rules using the available rewrite API methods we covered in part one. One method is to add the following list of rewrite rules when you register your post type:</p>
<pre name="code" class="php">
// Add day archive (and pagination)
add_rewrite_rule("books/([0-9]{4})/([0-9]{2})/([0-9]{2})/page/?([0-9]{1,})/?",'index.php?post_type=book&amp;year=$matches[1]&amp;monthnum=$matches[2]&amp;day=$matches[3]&amp;paged=$matches[4]','top');
add_rewrite_rule("books/([0-9]{4})/([0-9]{2})/([0-9]{2})/?",'index.php?post_type=book&amp;year=$matches[1]&amp;monthnum=$matches[2]&amp;day=$matches[3]','top');

// Add month archive (and pagination)
add_rewrite_rule("books/([0-9]{4})/([0-9]{2})/page/?([0-9]{1,})/?",'index.php?post_type=book&amp;year=$matches[1]&amp;monthnum=$matches[2]&amp;paged=$matches[3]','top');
add_rewrite_rule("books/([0-9]{4})/([0-9]{2})/?",'index.php?post_type=book&amp;year=$matches[1]&amp;monthnum=$matches[2]','top');

// Add year archive (and pagination)
add_rewrite_rule("books/([0-9]{4})/page/?([0-9]{1,})/?",'index.php?post_type=book&amp;year=$matches[1]&amp;paged=$matches[2]','top');
add_rewrite_rule("books/([0-9]{4})/?",'index.php?post_type=book&amp;year=$matches[1]','top');
</pre>
<p>This can easily get a bit messy &ndash; especially when you consider that you would need to add extra rules if you wanted your archives to support pretty URLs for their feeds. However, the above illustrates an important fact about adding custom rules: The order in which the rules are added is important.</p>
<p>Recall that these rules are added to the rewrite array in the order in which you call <code>add_rewrite_rule</code>. When parsing a request, WordPress uses the <em>first</em> matching rule. Try switching the order in which the year and month archive rules are added. You&#8217;ll find that <code>www.example.com/books/2012/04/</code> takes you to the 2012 archive. This is because that URL matches the patterns for both the year and month archives, but the former was added first. <strong>Remember to always add the more specific rule first.</strong></p>
<p>On the other hand, if you add a rewrite rule, whose regex already exists as a rule, that rule shall be overridden by the new one.</p>
<hr />
<h2>Permastructures</h2>
<p>There is an easy way to achieve the above: <a href="http://codex.wordpress.org/Function_Reference/add_permastruct"><code>add_permastruct</code></a>. This function is used by WordPress to create &#8216;permastructures&#8217;, from which it generates rewrite rules (like the above), which handle pagination and feeds. When you register a custom post type, WordPress doesn&#8217;t automatically create all the rewrite rules.  Instead it registers a permastructure &ndash; and only when the rules are being generated (i.e. when they are being flushed) does WordPress use those permastructures to generate the actual rewrite rules.</p>
<p>An example of a permastructure is the one you use in Settings -&gt; Permalinks. These accept any &#8216;hard-coded&#8217; slugs or any tags that exist by default or have been added with <code>add_rewrite_tag</code>, which we covered in part one. For example, the permastructure <code>%year%/%category%/%author%</code> would generate the following rewrite rules:</p>
<ul>
<li> <code> www.example.com/2012/url-rewriting/stephen </code> </li>
<li> <code> www.example.com/2012/url-rewriting/stephen/page/2 </code> </li>
<li> <code> www.example.com/2012/url-rewriting/stephen/feed/rss </code> </li>
</ul>
<ul>
<li> <code> www.example.com/2012/url-rewriting/ </code> </li>
<li> <code> www.example.com/2012/url-rewriting/page/2 </code> </li>
<li> <code> www.example.com/2012/url-rewriting/feed/rss </code> </li>
</ul>
<ul>
<li> <code> www.example.com/2012/ </code> </li>
<li> <code> www.example.com/2012/page/2 </code> </li>
<li> <code> www.example.com/2012/feed/rss </code> </li>
</ul>
<h3>The <code>add_permastruct</code> Function</h3>
<p>The <code>add_permastruct</code> function accepts four arguments:</p>
<ul>
<li><code>name</code> &ndash; A unique slug to identify your permastructure</li>
<li><code>struct</code> &ndash; The permastructure itself e.g. &#8216;<code>%year%/%category%/%author%</code>&#8216;</li>
<li><code>with_front</code> &ndash; true or false. This is the same argument as when registering the post type</li>
<li><code>ep_mask</code> &ndash; See EP Mask section below</li>
</ul>
<p>A couple of warnings on using <code>add_permastruct</code> need to be made here. First: you&#8217;ll want to make sure that a custom permastructure doesn&#8217;t clash with WordPress&#8217; rewrite rules for posts and pages. This can be done by prepending your custom permastructure with something hard-coded. For example:</p>
<pre name="code" class="php">
'something-hard-coded/%year%/%monthnum%/%day%'
</pre>
<p>Secondly &ndash; the rules are added in that order &ndash; so if your tags are &#8216;too generic&#8217;, the latter rules may never be applied. For example, the above structure (which you can try on your Settings -&gt; Permalinks page), generally works well, except that:</p>
<pre name="code" class="php">
www.example.com/2012/page/2
</pre>
<p>Is interpreted as the page of posts by author &#8217;2&#8242;, in category &#8216;page&#8217; in 2012. If you want to use <code>add_permastruct</code> and have your pagination and feeds rules cascade nicely then you&#8217;ll need to use tags which are not &#8216;generic&#8217; (by which I mean that the regex expressions are not generic). <code>%author%</code> and <code>%category%</code> are good examples of a generic tag as these will typically match any character.</p>
<h3>Custom Permastructure Example: Post Type Date Archives</h3>
<p>The year, month, and day tags on the other hand are very specific &ndash; matching only positive integers of lengths four and two, so we can use <code>add_permastruct</code> for our post type&#8217;s date archive. Because of the specific nature of the date tags, we need these rules to be added <em>before</em> the post type permalink rule &ndash; so add the following immediately <em>before</em> registering your post type:</p>
<pre name="code" class="php">
// Please note that this will only work on WordPress 3.4+ http://core.trac.wordpress.org/ticket/19871
add_rewrite_tag('%book_cpt%','(book)s','post_type=');
add_permastruct('book_archive', '%book_cpt%/%year%/%monthnum%/%day%');
</pre>
<p>In the above, the custom tag <code>%book_cpt%</code> acts as a hard-coded slug to differentiate this permastructure from other rules (as per the first warning). The generated rules will only apply if <code>%book_cpt%</code> matches &#8216;books&#8217; and, in which case the &#8216;book&#8217; part is captured and interpreted as the value for <code>post_type</code>. Please note that <code>add_rewrite_tag</code> only accepts the third argument since WordPress 3.4. However, you could use the following work-around:</p>
<pre name="code" class="php">
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag('%book_cpt%','(book)s','post_type=');
</pre>
<p>Having set up the book archives, you might also expect that</p>
<pre name="code" class="php">
www.example.com/books?year=2012
</pre>
<p>Would take us to the 2012 book archive as well. Testing it, however, reveals that instead it takes us to the post year archive page:</p>
<pre name="code" class="php">
www.example.com/2012/
</pre>
<p>WordPress has redirected us to a different page due to something known as <a href="http://support.google.com/webmasters/bin/answer.py?hl=en&#038;answer=139066">canonicalization</a>.</p>
<hr />
<h2>Canonical Redirect</h2>
<p>Typically there are many URLs that could point to the same content on your website. For example:</p>
<pre name="code" class="php">
www.example.com/year/2012

www.example.com/year/2012/page/1

www.example.com/2012/////////page/1

www.example.com/index.php/2012/

www.example.com/index.php////2012///page/1
</pre>
<p>Will all take you to the first page of your 2012 archive. From a SEO perspective this isn&#8217;t great &ndash; we can&#8217;t assume that search engines will recognise these URLs as the same resource, and these URLs may end up competing against each other. Google may also actively penalise you for <a href="http://support.google.com/webmasters/bin/answer.py?hl=en&amp;answer=66359">duplicate content</a>, and while it is good at determining when this duplication isn&#8217;t &#8216;malicious&#8217;, it still recommends to redirect these superfluous URLs to one preferred &#8216;canonical&#8217; (or standard) URL. This is called <strong>canonicalization</strong>.</p>
<p>Doing so not only helps consolidate ratings such as link popularity, but also helps your users. If they use an ugly or &#8216;incorrect&#8217; URL &ndash; they are taken to the &#8216;correct&#8217; URL &ndash; and what&#8217;s in their address bar, is what they&#8217;re more likely to return to.</p>
<p>Since 2.1.0 WordPress has handled canonical redirection, even taking an educated guess at the sought after content if the original query returned a 404. Unfortunately, in this instance, WordPress is redirecting to the wrong URL. This is because the URL we actually want is not natively understood by WordPress, and it has ignored the &#8216;post type&#8217; part of the URL. Fortunately, however we can use the <a href="http://adambrown.info/p/wp_hooks/hook/redirect_canonical"><code>redirect_canonical</code></a> filter to fix this.</p>
<pre name="code" class="php">
add_filter('redirect_canonical', 'wptuts_redirect_canonical', 10, 2);
function wptuts_redirect_canonical($redirect_url, $requested_url) {

	global $wp_rewrite;

	// Abort if not using pretty permalinks, is a feed, or not an archive for the post type 'book'
	if( ! $wp_rewrite-&gt;using_permalinks() || is_feed() || ! is_post_type_archive('book') )
		return $redirect_url;

	// Get the original query parts
	$redirect = @parse_url($requested_url);
	$original = $redirect_url;
	if( !isset($redirect['query'] ) )
		$redirect['query'] ='';

	// If is year/month/day - append year
	if ( is_year() || is_month() || is_day() ) {
		$year = get_query_var('year');
		$redirect['query'] = remove_query_arg( 'year', $redirect['query'] );
		$redirect_url = user_trailingslashit(get_post_type_archive_link('book')).$year;
	}

	// If is month/day - append month
	if ( is_month() || is_day() ) {
		$month = zeroise( intval(get_query_var('monthnum')), 2 );
		$redirect['query'] = remove_query_arg( 'monthnum', $redirect['query'] );
		$redirect_url .= '/'.$month;
	}

	// If is day - append day
	if ( is_day() ) {
		$day = zeroise( intval(get_query_var('day')), 2 );
		$redirect['query'] = remove_query_arg( 'day', $redirect['query'] );
		$redirect_url .= '/'.$day;
	}

	// If paged, apppend pagination
	if ( get_query_var('paged') &gt; 0 ) {
		$paged = (int) get_query_var('paged');
		$redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );

		if ( $paged &gt; 1 )
			$redirect_url .= user_trailingslashit("/page/$paged", 'paged');
	}

	if( $redirect_url == $original )
		return $original;

	// tack on any additional query vars
	$redirect['query'] = preg_replace( '#^\??&amp;*?#', '', $redirect['query'] );
	if ( $redirect_url &amp;&amp; !empty($redirect['query']) ) {
		parse_str( $redirect['query'], $_parsed_query );
		$_parsed_query = array_map( 'rawurlencode', $_parsed_query );
		$redirect_url = add_query_arg( $_parsed_query, $redirect_url );
	}

	return $redirect_url;
}
</pre>
<p>The above function is lengthy, but not very complicated. It could be improved upon, and is only intended as an example of what you can do with the <code>redirect_canonical</code> filter. It first checks that pretty permalinks are turned on, that we are after our &#8216;book&#8217; archive and it&#8217;s not a feed. It then checks in turn:</p>
<ol>
<li>Is it a year, month or day archive? If so, remove the &#8216;year&#8217; variable from the query string and set the redirect URL to <code>www.example.com/books/[year]</code></li>
<li>Is it a month or day archive? If so, remove the &#8216;monthnum&#8217; variable from the query string and append the value to the redirect URL: <code>www.example.com/books/[year]/[monthnum]</code></li>
<li>Is it a day archive? If so, remove the &#8216;day&#8217; variable from the query string and append the value to the redirect URL: <code>www.example.com/books/[year]/[monthnum]/[day]</code></li>
<li>Finally, if there is a paged variable, append this to the redirect URL</code></li>
</ol>
<hr/>
<h2>Tags in the Post Type Permalinks</h2>
<p>Another feature that isn't supported for post types or taxonomies 'out of the box' is to use tags in the permalink structure. While tags used in the 'slug' of a post type's (or taxonomy's) rewrite array are correctly interpreted, WordPress doesn't replace these tags with their appropriate values when generating the permalinks &ndash; we need to replace it ourselves. However, using tags like this also breaks the post type's archive page &ndash; so we'll use a different method. As an example, let's suppose that we want our custom post type 'book' to have the structure:</p>
<pre name="code" class="php">
www.example.com/books/[some-genre]/[a-book]
</pre>
<p>I'm using the example of a custom taxonomy, but the same methods can be used for any permastructure (for instance including the date, author, or even a custom field). First of all, we add the rewrite rule:</p>
<pre name="code" class="php">
function wptuts_custom_tags() {
	add_rewrite_rule("^books/([^/]+)/([^/]+)/?",'index.php?post_type=book&amp;genre=$matches[1]&amp;book=$matches[2]','top');
}
add_action('init','wptuts_custom_tags');
</pre>
<p>Now, <code>www.example.com/book/fiction/the-wizard-of-oz</code>, for instance, points to the book '<code>the-wizard-of-oz</code>'. However the permalink generated by WordPress still produces <code>www.example.com/book/the-wizard-of-oz</code>. The next step is to alter the produced permalink.</p>
<p>We did something similar in part one when we wanted to use a custom tag in the post permalink structure. Then we used the <a href="http://adambrown.info/p/wp_hooks/hook/post_link"><code>post_link</code></a> filter; this time we use the equivalent for custom post types, the <a href="http://adambrown.info/p/wp_hooks/hook/post_type_link"><code>post_type_link</code></a> filter. Using this hook we can inject our structure into the books' permalinks.</p>
<pre name="code" class="php">
function wptuts_book_link( $post_link, $id = 0 ) {

	$post = get_post($id);

	if ( is_wp_error($post) || 'book' != $post-&gt;post_type || empty($post-&gt;post_name) )
		return $post_link;

	// Get the genre:
	$terms = get_the_terms($post-&gt;ID, 'genre');

	if( is_wp_error($terms) || !$terms ) {
		$genre = 'uncategorised';
	}
	else {
		$genre_obj = array_pop($terms);
		$genre = $genre_obj-&gt;slug;
	}

	return home_url(user_trailingslashit( "books/$genre/$post-&gt;post_name" ));
}
add_filter( 'post_type_link', 'wptuts_book_link' , 10, 2 );
</pre>
<hr/>
<h2>Manipulating WordPress Rewrites</h2>
<p>Let's extend the above permalink structure to achieve the following:</p>
<ul>
<li>A specific book: <code>www.example.com/books/[some-genre]/[a-book]</code></li>
<li>All books in a genre: <code>www.example.com/books/[some-genre]</code></li>
<li>All books: <code>www.example.com/books/</code></li>
</ul>
<p>Recall that the order in which rewrite rules are added matter. Specifically, rules added first take priority.</p>
<p>So, first we register our custom taxonomy 'genre' with:</p>
<pre name="code" class="php">
$args = array(
	...
	'rewrite' =&gt; array(
		'slug'=&gt;'books'
	),
	...
)
register_taxonomy('genre',$args);
</pre>
<p>This adds the following permastructure:</p>
<ul>
<li>Books in a genre: <code>www.example.com/books/[some-genre]</code></li>
</ul>
<p>After registering the taxonomy, we then register our custom post type as follows:</p>
<pre name="code" class="php">
$args = array(
	...
	'rewrite' =&gt; array(
		'slug'=&gt;'books'
	),
	...
)
register_post_type('book',$args);
</pre>
<p>This would register the following rules:</p>
<ul>
<li>All books: <code>www.example.com/books/</code> (which we want)</li>
<li>A specific book: <code>www.example.com/books/[a-book]</code> (which we don't)</li>
</ul>
<p>However the second conflicts with (and is 'beaten' by) the competing rule added when we registered our taxonomy. The resulting structure is:</p>
<ul>
<li>Book called 'slug' : <code>www.example.com/books/fiction/slug</code></li>
<li>Books in genre 'slug': <code>www.example.com/books/slug</code></li>
<li>All Books: <code>www.example.com/books/</code></li>
</ul>
<hr/>
<h2>EP_Masks</h2>
<p>Earlier when we looked at registering post types, taxonomies (or otherwise, permstructures), WordPress let us specify our own '<code>ep_mask</code>'. So what are they?</p>
<p>In part one we looked at how we can add endpoints with <a href="http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint"><code>add_rewrite_endpoint</code></a>. The second argument in that function is a constant (or combination of constants using bitwise operators), which determine where the endpoint is added. For instance:</p>
<pre name="code" class="php">
add_rewrite_endpoint( 'form', EP_PAGES );
</pre>
<p>Adds the rewrite <code>form(/(.*))?/?$</code> to every page permalink and:</p>
<pre name="code" class="php">
add_rewrite_endpoint( 'json', EP_PAGES | EP_PERMALINKS);
</pre>
<p>Adds the rewrite <code>json(/(.*))?/?$</code> to every post and page permalink. So these constants specify a 'location' (i.e. 'at the end of a post permalink') and they are called <em>endpoint masks</em> (or ep masks).</p>
<p>When you register a post type, WordPress registers a permastructure &ndash; and associated with it an endpoint mask. Then when the rewrite rules are generated, it also adds any endpoint rewrite rules that have been added to that endpoint mask.</p>
<p>For instance, when WordPress registers the default 'Page' post type &ndash; it associates the endpoint mask <code>EP_PAGES</code> with the page permastructure. Then, any endpoint rewrite rules added to the <code>EP_PAGES</code> are actually added to that page permastructure. When you register a post type, you can specify your own endpoint mask, or use an existing one. By default it is <code>EP_PERMALINKS</code> &ndash; which means any endpoint rewrite rules that are added to <code>EP_PERMALINKS</code> are added to your custom post type's rewrite rules.</p>
<p>Of course you may not want endpoint rules added for your post type (in which case you can use the endpoint mask <code>EP_NONE</code>), or you may wish to add some endpoint rewrite rules <em>only</em> to your custom post type. To do this, you first need to create an endpoint mask, which is nothing more than a constant which satisfies:</p>
<ol>
<li>The value of the constant is a positive number and a power of 2: 2<sup>x</sup> (e.g. 2097152 = 2<sup>21</sup>)</li>
<li>This value is <strong>unique</strong></li>
</ol>
<p>The power of 2 requirement is necessary because WordPress uses binary logic to determine where endpoint rules should be added. Unfortunately, this is nearly impossible to check &nbsp; so the best advice is to add endpoint masks only when necessary and give it a very high value (e.g. 2<sup>21</sup>). At the time of writing 2<sup>0</sup> up to 2<sup>13</sup> are used by Core.</p>
<p>Define your endpoint mask just before registering your post type or taxonomy:</p>
<pre name="code" class="php">
	define('EP_BOOK', 8388608); // 8388608 = 2^23

	$args = array(
		'labels' =&gt; $labels,
		'has_archive'=&gt;true,
		'rewrite' =&gt; array(
			'slug'=&gt;'books'
			'with_front'=&gt; false
			'feed'=&gt; true
			'pages'=&gt; true
			'ep_mask'=&gt; EP_BOOK
		)
	);

	register_post_type('book',$args);

	// Then you can endpoint rewrite rules to this endpoint mask
	add_rewrite_endpoint('loan', EP_BOOK);
</pre>
<p><em>(Note: The above uses WordPress 3.4 arguments. If you are using an older version of WordPress, you will have to use the now deprecated <code>permalink_epmask</code>.)</em>. As of WordPress 3.4 you can specify an endpoint mask when registering a taxonomy too.</p>
<hr/>
<h2>Summary</h2>
<p>In this tutorial I've covered the basics of the rewrite API for post types and taxonomies, but also some more advanced topics. WordPress' handling of rewrites is (necessarily) complex and the best way to understand it is to delve into the <a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/rewrite.php">source code</a> and test it out using what've you learnt and a rewrite analyzer plug-in.</p>
<p>There are a couple of tickets working their way through the WordPress development Trac at the moment, relating to the Rewrite API. In the future we see a much easier and conflict-free way of handing endpoint masks.</p>
<ul>
<li><a href="http://core.trac.wordpress.org/ticket/16303">Improve documentation and usability of WP_Rewrite Endpoint</a></li>
<li><a href="http://core.trac.wordpress.org/ticket/12779">Better support for custom post types in WP_Rewrite</a></li>
<ul>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-post-types-taxonomies/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<series:name><![CDATA[The Rewrite API]]></series:name>
	</item>
		<item>
		<title>The Rewrite API: The Basics</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/#comments</comments>
		<pubDate>Wed, 23 May 2012 10:28:21 +0000</pubDate>
		<dc:creator>Stephen Harris</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Rewrite]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25474</guid>
		<description><![CDATA[<div class="seriesmeta">This entry is part 1 of 2 in the series <a href="http://wp.tutsplus.com/series/the-rewrite-api/" class="series-848" title="The Rewrite API">The Rewrite API</a></div><p>This is part one of a two part series looking at WordPress&#8217; Rewrite API. In this tutorial we look at how rewrites work and the basic methods available to create custom rewrite rules.<span id="more-25474"></span></p>
<hr />
<h2>What Is Rewriting?</h2>
<p>WordPress, like all content management systems, decides what content to display based on the variables (usually called query variables) passed to it. For instance: <code>http://example.com/index.php?category=3</code> tells WordPress we are after posts in a category with an ID of 3 and <code>http://example.com/index.php?feed=rss</code> tells WordPress we want the site&#8217;s feed in RSS format.</p>
<p>Unfortunately this can leave us with rather ugly URLs:</p>
<pre name="code" class="php">

http://example.com/index.php?post_type=portfolio&#038;taxonomy=wordpress&#038;portfolio=my-fancy-plugin
</pre>
<p>This is where WordPress&#8217; rewriting steps in. It allows us to replace the above with:</p>
<pre name="code" class="php">

http://example.com/portoflio/wordpress/my-fancy-plugin
</pre>
<p>Which is now not only much more readable (and memorable) but also more SEO friendly. This is, in a nutshell, what rewrites do.</p>
<hr />
<h2>How Does It Work?</h2>
<p>Now <code>http://example.com/portoflio/wordpress/my-fancy-plugin</code> doesn&#8217;t exist as a directory or a file. So how does WordPress serve up the correct content? When WordPress receives a &#8216;pretty permalink&#8217; like the above it needs to convert that into something it understands, namely a <em><a href="http://codex.wordpress.org/Class_Reference/WP_Query">query object</a></em>. More simply it has to take the pretty URL, and map the appropriate parts to the correct query variable. So for our example:</p>
<pre name="code" class="php">

http://example.com/portoflio/wordpress/my-fancy-plugin
</pre>
<ul>
<li><code>post_type</code> is set to &#8216;portfolio&#8217;</li>
<li><code>portfolio-taxonomy</code> is set to &#8216;wordpress&#8217;</li>
<li><code>portfolio</code> is set to &#8216;my-fancy-plugin&#8217; (the post name)</li>
</ul>
<p>Then WordPress knows we are after posts of type &#8216;<code>portfolio</code>&#8216;, in the &#8216;<code>wordpress</code>&#8216; &#8216;<code>portfolio-taxonomy</code>&#8216; taxonomy term with name &#8216;<code>my-fancy-plugin</code>&#8216;. (As you may have guessed the first two are actually redundant). WordPress then performs that query, chooses the appropriate template with which to display the results and then serves that to the viewer. But clearly WordPress doesn&#8217;t just guess how to interpret the URLs, it needs to be told&#8230;</p>
<h3>It Starts With .htaccess</h3>
<p>Assuming you can and have enabled pretty permalinks on your Settings -&gt; Permalinks page (see the <a href="http://codex.wordpress.org/Using_Permalinks#Using_.22Pretty.22_permalinks">Codex for minimum requirements</a> &ndash; for WordPress on Nginx servers there is <a href="http://wordpress.org/extend/plugins/nginx-compatibility/">this plug-in</a>) &ndash; then things start with the <code>.htaccess</code> file. It plays a simple and yet significant role. WordPress includes something similar to the the following in this file:</p>
<pre name="code" class="php">
	# BEGIN WordPress
	&lt;IfModule mod_rewrite.c&gt;
		RewriteEngine On
		RewriteBase /
		RewriteRule ^index\.php$ - [L]
		RewriteCond %{REQUEST_FILENAME} !-f
		RewriteCond %{REQUEST_FILENAME} !-d
		RewriteRule . /index.php [L]
	&lt;/IfModule&gt;
	# END WordPress
</pre>
<p>This simply checks if the file or directory actually exists &ndash; and if it does, you are simply taken there. For instance:</p>
<pre name="code" class="php">

http://example.com/blog/wp-content/uploads/2012/04/my-picture.png
</pre>
<p>Would simply take you the PNG attachment &#8216;<strong>my-picture.png</strong>&#8216;. But, as in the case of:</p>
<pre name="code" class="php">

http://example.com/blog/portoflio/wordpress/my-fancy-plugin
</pre>
<p>Where the directory does not exist &ndash; you are taken to your WordPress&#8217; <strong>index.php</strong> file. It&#8217;s this file which boots WordPress.</p>
<h3>Interpreting the URL</h3>
<p>At this point, WordPress doesn&#8217;t yet know what you&#8217;re after. After some initial loading of WordPress and its settings, it fires the <code>parse_request</code> method of the <code>WP</code> class (<a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/class-wp.php#L110">located in the <strong>class-wp.php</strong> file</a>). It&#8217;s this method which takes the <code>/portoflio/wordpress/my-fancy-plugin</code> and converts it into a WordPress-understandable query object (<em>almost</em>, it actually sets the <code>query_vars</code> array and afterwards <a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/class-wp.php#L451"><code>$wp->query_posts</code></a> turns this into a query).</p>
<p>In short this function compares the received URL (<code>/portoflio/wordpress/my-fancy-plugin</code>) with an array of &#8216;regular expressions&#8217;. This is the <em>rewrite array</em> &ndash; and it will look something like this:</p>
<pre name="code" class="php">
	category/(.+?)/page/?([0-9]{1,})/?$ =&gt; index.php?category_name=$matches[1]&amp;paged=$matches[2]
	category/(.+?)/?$ =&gt; index.php?category_name=$matches[1]
	tag/([^/]+)/page/?([0-9]{1,})/?$=&gt; index.php?tag=$matches[1]&amp;paged=$matches[2]
	tag/([^/]+)/?$ =&gt; index.php?tag=$matches[1]
	([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$ =&gt; index.php?year=$matches[1]&amp;monthnum=$matches[2]&amp;day=$matches[3]
	(.+?)(/[0-9]+)?/?$ =&gt; index.php?pagename=$matches[1]&amp;page=$matches[2]
</pre>
<p>The keys of this array are regular expressions, and the received URL is compared against each in turn until there is a match with the pattern of the URL received. The corresponding value, is how the URL is then interpreted. The <code>$matches</code> array contains the captured values (indexed from 1) from the matching.</p>
<p>For example, visiting <code>www.example.com/blog/tag/my-tag</code>, WordPress will look for the first pattern that matches &#8216;<code>tag/my-tag</code>&#8216;. With the above array, it matches the third pattern: <code>tag/([^/]+)/?$</code>. This tells WordPress to interpret the URL as <code>www.example.com/blog/index.php?tag=my-tag</code> and correspondingly the &#8216;<code>my-tag</code>&#8216; archive is served.</p>
<p>Of course, WordPress lets you customise this array, and the rest of this tutorial is dedicated to showing you how.</p>
<hr />
<h2>Customising the Rewrite Rules</h2>
<h3>Settings -&gt; Permalinks</h3>
<p>Your first port of call should be the &#8216;Permalink&#8217; settings page. This page allows you to alter the rules for the default &#8216;<code>post</code>&#8216; post type, and &#8216;<code>category</code>&#8216; and &#8216;<code>tags</code>&#8216; taxonomies. The &#8216;default&#8217; option has pretty permalinks disabled, but you can select from a list of preset structures or create a custom structure. <strong>Please note that custom structures should not contain your site URL</strong>. WordPress allows you to alter your permalink structure by adding in provided tags such as <code>%postname%</code> (the post&#8217;s name), <code>%year%</code> (the year the post was published) and <code>%author%</code> (the author of the post). A permalink structure such as:</p>
<pre name="code" class="php">
/%year%/%author%/%postname%/
</pre>
<p>Would produce a post link such as:</p>
<pre name="code" class="php">
www.example.com/2012/stephen/my-post
</pre>
<p>The documentation for these options can be found in the <a href="http://codex.wordpress.org/Using_Permalinks#Choosing_your_permalink_structure">WordPress Codex</a>. (Later on I&#8217;ll be showing you how to create your own custom tags).</p>
<p>However, the provided options are quite limited. In this tutorial I shall focus on the functions provided by WordPress that offer greater control over permalink structures and how they are interpreted. I won&#8217;t be covering the rewrite options available for custom post types or taxonomies, as this will be covered in part 2.</p>
<h3>Why Flush the Rewrite Rules?</h3>
<p>After any alteration to the rewrite rules (for example, by either using one of the following methods, or registering a custom post type or taxonomy) you may find that the new rules do not take effect. This is because you you need to flush the rewrite rules. This can be done either one of two ways:</p>
<ul>
<li>Simply visit the Settings -&gt; Permalink page</li>
<li>Call <code>flush_rewrite_rules()</code> (covered in part 2)</li>
</ul>
<p>What does this do? Recall that the <code>parse_request</code> method compares the request against a rewrite array. This array lives in the database. Flushing the rewrite rules updates the database to reflect your changes &ndash; and until you do so, they won&#8217;t be recognised. But <code>parse_request</code> <em>also</em> writes to the <code>.htaccess</code> file. This makes it an expensive operation. So, although I won&#8217;t cover the use of <code>flush_rewrite_rules()</code> until part 2, I will give you this warning: <strong>Do not call <code>flush_rewrite_rules</code> on every page load. Plug-ins should only call this when the plug-in is activated and deactivated</strong>.</p>
<h3>Add Rewrite Rule</h3>
<p>The <a href="http://codex.wordpress.org/Rewrite_API/add_rewrite_rule"><code>add_rewrite_rule</code></a> allows you to add additional rules to the rewrite array. This function accepts three arguments:</p>
<ul>
<li><strong>rule</strong> &ndash; a regular expression with which to compare the request URL against</li>
<li><strong>rewrite</strong> &ndash; the query string used to interpret the rule. The <code>$matches</code> array contains the captured matches and starts from index &#8217;1&#8242;.</li>
<li><strong>position</strong> &ndash; &#8216;<code>top</code>&#8216; or &#8216;<code>bottom</code>&#8216;. Where to place the rule: at the top of the rewrite array or the bottom. WordPress scans from the top of the array to the bottom and stops as soon as it finds a match. In order for your rules to take precedence over existing rules you&#8217;ll want to set this to &#8216;<code>top</code>&#8216;. Default is &#8216;<code>bottom</code>&#8216;.</li>
</ul>
<p><strong>Note:</strong> if you use <code>add_rewrite_rule</code> several times, each with position &#8216;<code>top</code>&#8216; &ndash; the <em>first</em> call takes precedence over subsequent calls.</p>
<p>Let&#8217;s suppose our posts have an event date associated with them and we want to have this structure: <code>www.example.com/blog/the-olympics-begin/2012-07-27</code> interpreted as <code>www.example.com/blog/index.php?postname=the-olympics-begin&amp;eventdate=2012-07-27</code> then we can add this rule as follows:</p>
<pre name="code" class="php">
	function wptuts_add_rewrite_rules() {
		add_rewrite_rule(
			'^([^/]*)/([0-9]{4}-[0-9]{2}-[0-9]{2})/?$' // String followed by a slash, followed by a date in the form '2012-04-21', followed by another slash
			'index.php?pagename=$matches[1]&amp;eventdate=$matches[2]',
			'top'
		);
	}
	add_action( 'init', 'wptuts_add_rewrite_rules' );
</pre>
<p>The following would interpret <code>www.example.com/olympics/2012/rowing</code> as <code>www.example.com/index.php?p=17&#038;olymyear=2012&amp;game=rowing</code></p>
<pre name="code" class="php">
	add_rewrite_rule(
		'^olympics/([0-9]{4})/([^/]*)',
		'index.php?p=17&amp;olymyear=$matches[1]&amp;game=$matches[2]',
		'top'
	);
</pre>
<p>If you&#8217;re unsure of your regular expressions, you may find <a href="http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html">this introduction</a> and <a href="http://regex.larsolavtorvik.com/">this tool</a> useful.</p>
<h3>Add Rewrite Tag</h3>
<p>You may think that the value of <code>eventdate</code> (2012-07-27 in the above example), <code>olymyear</code> and <code>game</code> may be accessible from WordPress&#8217; internals via the <a href="http://codex.wordpress.org/Function_Reference/get_query_var"><code>get_query_var</code></a> (in the same way that <code>get_query_var('paged')</code> gets the page number you are on). However, WordPress does not automatically recognise the variable <code>eventdate</code> even though it&#8217;s interpreted as a GET variable. There are a couple of ways to make WordPress recognise custom variables. One is to use the <a href="http://wordpress.stackexchange.com/questions/41370/using-get-variables-in-the-url/41373#41373"><code>query_vars</code></a> filter as demonstrated in the &#8216;Add Custom Endpoint&#8217; section below. Alternatively, we can go a step further and use <a href="http://codex.wordpress.org/Rewrite_API/add_rewrite_tag"><code>add_rewrite_tag</code></a> to register a custom tag like the default <code>%postname%</code> and <code>%year%</code></p>
<p>This function accepts three arguments:</p>
<ul>
<li><strong>tag name</strong> &ndash; (with leading and trailing %) e.g: <code>%eventdate%</code></li>
<li><strong>regex</strong> &ndash; Regular expression to validate the value, e.g. &#8216;<code>([0-9]{4}-[0-9]{2}-[0-9]{2})</code>&#8216;</li>
<li><strong>query</strong> &ndash; (optional) How the tag is interpreted, e.g. &#8216;<code>eventdate=</code>&#8216;. If provided, must end with a &#8216;=&#8217;.</li>
</ul>
<pre name="code" class="php">
	function wptuts_register_rewrite_tag() {
		add_rewrite_tag( '%eventdate%', '([0-9]{4}-[0-9]{2}-[0-9]{2})');
	}
	add_action( 'init', 'wptuts_register_rewrite_tag');
</pre>
<p>Not only will <code>get_query_var('eventdate')</code> return the value of the date in the URL, but you can use the tag <code>%eventdate%</code> in the Settings -&gt; Permalink (along with the default <code>%year%</code>, <code>%postname%</code> etc.) and WordPress will correctly interpret it. <em>Unfortunately</em> when generating a post&#8217;s permalink, WordPress doesn&#8217;t know how to replace <code>%eventdate%</code> with the appropriate value: so our post permalinks end up like:</p>
<pre name="code" class="php">
www.example.com/the-olympics-begin/%eventdate%
</pre>
<p>We need to replace <code>%eventdate%</code> with an appropriate value, and we can do so using using the <a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/link-template.php#L163"><code>post_link</code></a> filter. (In this example, I shall assume that the value is stored in a custom field &#8216;<code>eventdate</code>&#8216;).</p>
<pre name="code" class="php">
	function wp_tuts_filter_post_link( $permalink, $post ) {

		// Check if the %eventdate% tag is present in the url:
		if ( false === strpos( $permalink, '%eventdate%' ) )
			return $permalink;

		// Get the event date stored in post meta
		$event_date = get_post_meta($post->ID, 'eventdate', true);

		// Unfortunately, if no date is found, we need to provide a 'default value'.
		$event_date = ( ! empty($event_date) ? $event_date : '2012-01-01' );

		$event_date =urlencode($event_date);

		// Replace '%eventdate%'
		$permalink = str_replace( '%eventdate%', $event_date , $permalink );

		return $permalink;
	}
	add_filter( 'post_link', 'wp_tuts_filter_post_link' , 10, 2 );
</pre>
<p>In part 2 of this series I will cover custom tags for custom post types.</p>
<h3>Add Custom Endpoint</h3>
<p>Endpoints are tags which are appended to the URL (<code>/trackback/[value]</code> is the most common). It has several other potential uses: displaying different templates depending on the value set, custom notifications, and displaying posts in different &#8216;formats&#8217; (printable, XML, JSON etc).</p>
<p>You can create endpoints with <a href="http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint"><code>add_rewrite_endpoint</code></a>. This function accepts two arguments:</p>
<ul>
<li><strong>name</strong> &ndash; The name of the endpoint e.g. &#8216;<code>json</code>&#8216;, &#8216;<code>form</code>&#8216;, etc.</li>
<li><strong>where</strong> &ndash; Endpoint mask specifying where the endpoint should be added. This should be one of the EP_* constants listed below (or a combination using bitwise operators). When you register custom post types you can create a mask for that post type:</li>
</ul>
<p>The default endpoint masks are:</p>
<ul>
<li><strong>EP_PERMALINK</strong> &ndash; for post permalinks</li>
<li><strong>EP_ATTACHMENT</strong> &ndash; for attachments</li>
<li><strong>EP_DATE</strong> &ndash; for date archives</li>
<li><strong>EP_YEAR</strong> &ndash; for year archives</li>
<li><strong>EP_MONTH</strong> &ndash; for month archives</li>
<li><strong>EP_DAY</strong> &ndash; for &#8216;day&#8217; archives</li>
<li><strong>EP_ROOT</strong> &ndash; for the root of the site</li>
<li><strong>EP_COMMENTS</strong> &ndash; for comments</li>
<li><strong>EP_SEARCH</strong> &ndash; for searches</li>
<li><strong>EP_CATEGORIES</strong> &ndash; for categories</li>
<li><strong>EP_TAGS</strong> &ndash; for tags</li>
<li><strong>EP_AUTHORS</strong> &ndash; for archive of author&#8217;s posts</li>
<li><strong>EP_PAGES</strong> &ndash; for pages</li>
<li><strong>EP_ALL</strong> &ndash; for everything</li>
</ul>
<p>End points are extremely flexible, you can use them with <a href="http://php.net/manual/en/language.operators.bitwise.php">bitwise operators</a> so, for example, you can add an endpoint to post and page permalinks with <code>EP_PERMALINK | EP_PAGES</code>.</p>
<pre name="code" class="php">
	function wptuts_add_endpoints() {
		add_rewrite_endpoint('myendpoint', EP_PERMALINK); // Adds endpoint to permalinks
		add_rewrite_endpoint( 'anotherendpoint', EP_AUTHORS | EP_SEARCH); // Adds endpoint to urls for authors or search results
	}
	add_action( 'init', 'wptuts_add_endpoints');
</pre>
<p>As a brief example, endpoints can be useful for form submissions. Suppose we have a contact form page with name <code>contact-form</code> and with permalink: <code>www.example.com/contact</code> and want the the URLs:</p>
<ul>
<li><code>www.example.com/contact/submission/success</code> &ndash; to reflect a successful form submission</li>
<li><code>www.example.com/contact/submission/error</code> &ndash; to reflect an unsuccessful form submission</li>
</ul>
<p>This can be done with endpoints. The following is a very simple example of how to use endpoints, and so the form is incredibly basic in its checks (and in fact doesn&#8217;t do anything with the data). Normally a form like this would work best in a plug-in, using shortcodes &ndash; but for the purposes of this example, create a page with the following template and the rest of the code you can put in your <strong>functions.php</strong></p>
<pre name="code" class="php">
&lt;?php
	/**
	* Template Name: Contact Form
	*/
	include('header.php');?&gt;

	&lt;h1&gt; My Simple Contact Form &lt;/h1&gt;
	&lt;?php if ( 'success' == get_query_var( 'form' ) ): ?&gt;
		&lt;div class="message"&gt;
			Your message has been sent!
		&lt;/div&gt;

	&lt;?php elseif( 'error' == get_query_var( 'form' )): ?&gt;
		&lt;div class="message"&gt;
			Oops! There seems to have been an error...
		&lt;/div&gt;
	&lt;?php endif ?&gt;

	&lt;! -- Display form here --&gt;
	&lt;form method='post' action=''&gt;

		&lt;label&gt; Your name: &lt;/label&gt; &lt;input type="text" name="wptuts_contact[name]" value=""/&gt;
		&lt;label&gt; Your message: &lt;/label&gt; &lt;textarea name="wptuts_contact[message]" rows="20" cols="30"&gt;&lt;/textarea&gt;

		&lt;! -- Nonce field --&gt;
		&lt;?php wp_nonce_field('wptuts_send_message','wptuts_contact_nonce'); ?&gt;

		&lt;input type="hidden" name="action" value="wptuts_send_message"/&gt;

		&lt;! -- mmm... honey  --&gt;
		&lt;style scoped&gt;.wptuts-e-mail-conformation{display:none}&lt;/style&gt;
		&lt;span class="wptuts-e-mail-conformation"&gt;&lt;label for="email-confirmation"&gt;Email confirmation:&lt;/label&gt;&lt;input type="text" name="wptuts_contact[confirmation]" value="" /&gt;&lt;/span&gt;

		&lt;input type='submit' name='wptuts_contact[send]' value='Send' /&gt;
	&lt;/form&gt;

	&lt;?php include('footer.php');?&gt;
</pre>
<p>(In case you are wondering, the honey is referring to this very basic method of catching spam <a href="http://www.ngenworks.com/blog/invisible_captcha_to_prevent_form_spam/">outlined here</a>. It&#8217;s certainly not fool proof, but proper form processing and spam protection is off topic here). Now we create our endpoint:</p>
<pre name="code" class="php">
	function wptuts_add_endpoint() {
		add_rewrite_endpoint( 'form', EP_PAGES );
	}
	add_action( 'init', 'wptuts_add_endpoint');
</pre>
<p>Next we add our &#8216;<code>form</code>&#8216; variable to the array of recognised variables:</p>
<pre name="code" class="php">
	function wptuts_add_queryvars( $query_vars ) {
		$query_vars[] = 'form';
		return $query_vars;
	}
	add_filter( 'query_vars', 'wptuts_add_queryvars' );
</pre>
<p>Finally we provide a form handler, which will process the data, submit the form, and then redirect back to the contact page with the relevant endpoint value appended.</p>
<pre name="code" class="php">
	function wptuts_form_handler() {

		// Are we wanting to process the form
		if( ! isset( $_POST['action'] ) || 'wptuts_send_message' != $_POST['action'] )
			return;

		// ID of the contact form page
		$form_id = 2163;
		$redirect= get_permalink($form_id);

		// Check nonces
		$data = $_POST['wptuts_contact'];

		if( !isset($_POST['wptuts_contact_nonce'] ) || !wp_verify_nonce($_POST['wptuts_contact_nonce'],'wptuts_send_message') ) {
			// Failed nonce check
			$redirect .= 'form/error';
			wp_redirect($redirect);
			exit();
		}

		if( !empty( $data['confirmation'] ) ) {
			// Bees in the honey...
			$redirect .= 'form/error';
			wp_redirect($redirect);
			exit();
		}

		// Santize and validate data etc.

		// Then actually do something with the sanitized data

		// Successful!
		$redirect .= 'form/success';
		wp_redirect($redirect);
		exit();
	}
	add_action( 'init', 'wptuts_form_handler');
</pre>
<p>Of course even this example could be greatly improved by providing more detailed error messages that convey the reason for failure.</p>
<h3>Adding a Custom Feed</h3>
<p>With pretty permalinks enabled WordPress automatically produces pretty URLs for your site&#8217;s feed: <code>www.example.com/feed/rss</code>. The <a href="http://codex.wordpress.org/Rewrite_API/add_feed"><code>add_feed</code></a> function allows you to create a custom feed, which if pretty permalinks are enabled, will also have a &#8216;pretty&#8217; URL. This function accepts two arguments:</p>
<ul>
<li><strong>feed name</strong> &ndash; The name of the feed as it will be appear in <code>feed/[feed-name]</code></li>
<li><strong>feed callback</strong> &ndash; The function responsible for displaying the feed contents.</li>
</ul>
<p><em>The following is intended as an example of <code>add_feed</code>, and provides a very basic custom feed.</em></p>
<pre name="code" class="php">
	function wptuts_events_feed_callback() {
		$custom_feed = new WP_Query(array('meta_key' =&gt; 'eventdate'));

		header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true);
		echo '&lt;?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'&gt;'; ?&gt;

		&lt;rss version="2.0"&gt;
		&lt;channel&gt;
			&lt;title&gt;My custom feed&lt;/title&gt;
			&lt;link&gt;&lt;?php bloginfo_rss('url') ?&gt;&lt;/link&gt;
			&lt;description&gt;&lt;?php bloginfo_rss("description") ?&gt;&lt;/description&gt;
			&lt;lastBuildDate&gt;&lt;?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?&gt;&lt;/lastBuildDate&gt;
			&lt;language&gt;&lt;?php echo get_option('rss_language'); ?&gt;&lt;/language&gt;
			&lt;?php if($custom_feed-&gt;have_posts()): ?&gt;
				&lt;?php while( $custom_feed-&gt;have_posts()): $custom_feed-&gt;the_post(); ?&gt;
					&lt;item&gt;
						&lt;title&gt;&lt;?php the_title_rss() ?&gt;&lt;/title&gt;
						&lt;link&gt;&lt;?php the_permalink_rss() ?&gt;&lt;/link&gt;
						&lt;pubDate&gt;&lt;?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?&gt;&lt;/pubDate&gt;
						&lt;guid isPermaLink="false"&gt;&lt;?php the_guid(); ?&gt;&lt;/guid&gt;
						&lt;description&gt;&lt;![CDATA[&lt;?php the_excerpt_rss() ?&gt;]]&gt;&lt;/description&gt;
					&lt;/item&gt;
				&lt;?php endwhile; ?&gt;
			&lt;?php endif; ?&gt;
		&lt;/channel&gt;
		&lt;/rss&gt;
	&lt;?php
	}

	function wptuts_add_feed() {
		add_feed('events', 'wptuts_events_feed_callback');
	}
	add_action( 'init', 'wptuts_add_feed );
</pre>
<p>After flushing the permalinks, the feed will be available at <code>www.example.com/feed/events</code>.</p>
<hr />
<h2>Checking the Rewrite Rules</h2>
<p>Once you&#8217;ve added some of your own rewrite rules (and flushed them), you will probably want to check if they are working properly &ndash; and if they&#8217;re not, find out what&#8217;s going wrong. For this, I strongly recommended the <a href="http://wordpress.org/extend/plugins/monkeyman-rewrite-analyzer/">Monkeyman Rewrite Analyzer plug-in</a>, a free plug-in available in the WordPress repository. Once activated, this plug-in adds a page to your &#8216;Tools&#8217; section, which lists all your rewrite rules.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/279_The_Rewrite_API_Part_1_The_Basics/1.png" border="0" /></div>
<p>You can also test the rules by giving it an example URL, and the plug-in will filter the rules to show only matching patterns and indicating how WordPress would interpret the URL.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/279_The_Rewrite_API_Part_1_The_Basics/2.png" border="0" /></div>
<p>Have fun, and keep an eye out for Part 2, coming soon!</p>
<blockquote><p>Please note: There is a currently a bug in our syntax highlighter that displays &#8220;<code>empty()</code>&#8221; as &#8220;<code>emptyempty()</code>&#8220;. Don&#8217;t forget to adjust your code accordingly.</p>
</blockquote>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<series:name><![CDATA[The Rewrite API]]></series:name>
	</item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 0.641 seconds -->

