<?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>Wed, 16 May 2012 09:58:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</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>Adding Post Series Functionality to WordPress With Taxonomies</title>
		<link>http://wp.tutsplus.com/tutorials/plugins/adding-post-series-functionality-to-wordpress-with-taxonomies/</link>
		<comments>http://wp.tutsplus.com/tutorials/plugins/adding-post-series-functionality-to-wordpress-with-taxonomies/#comments</comments>
		<pubDate>Wed, 16 May 2012 09:58:08 +0000</pubDate>
		<dc:creator>Barış Ünver</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[custom taxonomy]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Taxonomies]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25414</guid>
		<description><![CDATA[<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>There is. In this article, we&#8217;re going to learn how to create the &#8220;post series&#8221; functionality by using the the taxonomies and shortcodes.</p>
<p>The article contains 3 parts:</p>
<ul>
<li>Creating the taxonomy</li>
<li>Creating the shortcode</li>
<li>Adding the taxonomies and using the shortcode</li>
</ul>
<p>I&#8217;ll explain almost every line of code, so you can develop it any way you like.</p>
<hr />
<h2><span>Step 1</span> Creating the Plugin File</h2>
<p>This barely counts as a step: We&#8217;ll just create the plugin file and fill in the details of the plugin:</p>
<pre name="code" class="php">
&lt;?php
/*
Plugin Name: Post Series
Plugin URI: http://wp.tutsplus.com/tutorials/plugins/adding-post-series-functionality-to-wordpress-with-taxonomies/
Description: Adds the &quot;post series&quot; functionality to WordPress with the help of a taxonomy and a shortcode.
Version: 1.0
Author: Barış Ünver
Author URI: http://beyn.org/
*/
?&gt;
</pre>
<p>Save this little chunk of code in the file <strong>post-series.php</strong> or any name you like, into the folder <strong>/wp-content/plugins/post-series/</strong>.</p>
<hr />
<h2><span>Step 2</span> Setting Up Our New Taxonomy: &#8220;Series&#8221;</h2>
<p>WordPress has a not-so-new functionality to create &#8220;taxonomies&#8221; so we can create more kinds of &#8220;classification groups&#8221; just like tags or categories (which are the built-in taxonomies of WordPress). We&#8217;re going to set up a new taxonomy called &#8220;Series&#8221; and we&#8217;ll be using this new taxonomy in our post series to help us.</p>
<p>First, we need to create a function to register the taxonomy. Let&#8217;s call it <code>series_tax</code>:</p>
<pre name="code" class="php">
function series_tax() {
	/* Creating an empty function LIKE A BOSS */
}
add_action('init', 'series_tax', 0);
</pre>
<blockquote><p>Take note that we also added an action to make the function run when WordPress is <em>ready</em>.</p>
</blockquote>
<p>Next, we&#8217;ll be using the native <code>register_taxonomy()</code> function to create our taxonomy. But before that, we should set up the &#8220;labels&#8221; of the taxonomy:</p>
<pre name="code" class="php">
function series_tax() {
	$labels = array(
		'name' =&gt; _x('Series', 'taxonomy general name'),
		'singular_name' =&gt; _x('Series', 'taxonomy singular name'),
		'all_items' =&gt; __('All Series'),
		'edit_item' =&gt; __('Edit Series'),
		'update_item' =&gt; __('Update Series'),
		'add_new_item' =&gt; __('Add New Series'),
		'new_item_name' =&gt; __('New Series Name'),
		'menu_name' =&gt; __('Series')
	);
}
add_action('init', 'series_tax', 0);
</pre>
<p>We didn&#8217;t use all the labels &ndash; You can find a full reference of taxonomy labels in our article <a href="http://wp.tutsplus.com/tutorials/theme-development/taking-wordpress-custom-taxonomies-to-the-next-level/">Taking WordPress Custom Taxonomies to the Next Level</a>.</p>
<p>We can register the taxonomy now:</p>
<pre name="code" class="php">
// create the &quot;Series&quot; taxonomy for posts only
function series_tax() {
	$labels = array(
		'name' =&gt; _x('Series', 'taxonomy general name'),
		'singular_name' =&gt; _x('Series', 'taxonomy singular name'),
		'all_items' =&gt; __('All Series'),
		'edit_item' =&gt; __('Edit Series'),
		'update_item' =&gt; __('Update Series'),
		'add_new_item' =&gt; __('Add New Series'),
		'new_item_name' =&gt; __('New Series Name'),
		'menu_name' =&gt; __('Series')
	);

	register_taxonomy(
		'series',
		array('post'), /* if you want to use pages or custom post types, simply extend the array like array('post','page','custom-post-type') */
		array(
			'hierarchical' =&gt; true, /* if set to &quot;true&quot;, you can use Series as categories; if set to &quot;false&quot;, you can use them as tags! */
			'labels' =&gt; $labels,
			'show_ui' =&gt; true,
			'query_var' =&gt; true,
			'rewrite' =&gt; array('slug' =&gt; 'series'), /* you may need to flush the rewrite rules at Options -&gt; Permalinks (just update the existing preferences without any change) */
		)
	);
}
add_action('init', 'series_tax', 0);
</pre>
<p>Congratulations, you just created the first half of your plugin! Now, let&#8217;s get to the second half&#8230;</p>
<hr />
<h2><span>Step 3</span> Creating the Shortcode: <code>[series]</code></h2>
<p>In this step, we&#8217;re going to build the <code>[series]</code> shortcode. With this shortcode, we&#8217;ll be able to insert the list of the series&#8217; posts. We&#8217;ll also be able to customize the shortcode with some attributes like &#8220;<code>title</code>&#8220;, &#8220;<code>title_wrap</code>&#8220;, &#8220;<code>slug</code>&#8220;, &#8220;<code>id</code>&#8220;, &#8220;<code>list</code>&#8220;, &#8220;<code>limit</code>&#8221; and &#8220;<code>future</code>&#8221; which will all be optional.</p>
<p>Let&#8217;s start by creating our function:</p>
<pre name="code" class="php">
function series_sc($atts) {
	extract(
		shortcode_atts(
			array(
				&quot;slug&quot; =&gt; '',
				&quot;id&quot; =&gt; '',
				&quot;title&quot; =&gt; '',
				&quot;title_wrap&quot; =&gt; 'h3',
				&quot;list&quot; =&gt; 'ul',
				&quot;limit&quot; =&gt; -1,
				&quot;future&quot; =&gt; 'on'
			),
			$atts
		)
	);
}
add_shortcode('series','series_sc');
</pre>
<p>We now have an empty shortcode with 7 optional attributes! We&#8217;ll get to know them while writing the rest of the code but I should explain them now:</p>
<ul>
<li><code>slug</code> &ndash; The slug of the series, defaults to nothing</li>
<li><code>id</code> &ndash; The ID of the series, defaults to nothing</li>
<li><code>title</code> &ndash; The title of the output, defaults to nothing</li>
<li><code>title_wrap</code> &ndash; The HTML tag to wrap the title with, defaults to &#8220;<code>h3</code>&#8220;</li>
<li><code>list</code> &ndash; The HTML tag to wrap the post list with, defaults to &#8220;<code>ul</code>&#8220;</li>
<li><code>limit</code> &ndash; The maximum number of posts, defaults to <code>-1</code> (all posts)</li>
<li><code>future</code> &ndash; The option to include the future posts or not, defaults to &#8220;<code>on</code>&#8220;</li>
</ul>
<p>Next, we&#8217;ll code the &#8220;find the proper taxonomy&#8221; part:</p>
<pre name="code" class="php">
if ($id) {
	// Use the &quot;id&quot; attribute if it exists
	$tax_query = array(array('taxonomy' =&gt; 'series', 'field' =&gt; 'id', 'terms' =&gt; $id));
}
elseif ($slug) {
	// Use the &quot;slug&quot; attribute if &quot;id&quot; does not exist
	$tax_query = array(array('taxonomy' =&gt; 'series', 'field' =&gt; 'slug', 'terms' =&gt; $slug));
}
else {
	// Use posts own Series tax if neither &quot;id&quot; nor &quot;slug&quot; exist
	$terms = get_the_terms($post-&gt;ID,'series');
	if ($terms &amp;&amp; !is_wp_error($terms)) {
		$tax_query = array(array('taxonomy' =&gt; 'series', 'field' =&gt; 'slug', 'terms' =&gt; $term[0]-&gt;slug));
	}
	else {
		$error = true;
	}
}
</pre>
<p>The &#8220;<code>slug</code>&#8221; and the &#8220;<code>id</code>&#8221; work in cooperation but they&#8217;re both optional: The shortcode will first look for the &#8220;<code>slug</code>&#8220;, then it&#8217;ll look for the &#8220;<code>id</code>&#8220;. If there&#8217;s no slug and no ID either, the shortcode will try to get the &#8220;series&#8221; taxonomy of the post that contains the shortcode.</p>
<p>Now, let&#8217;s code the &#8220;create the title (if it&#8217;s specified)&#8221; part:</p>
<pre name="code" class="php">
if ($title) {
	// Create the title if the &quot;title&quot; attribute exists
	$title_output = '&lt;'.$title_wrap.' class=&quot;post-series-title&quot;&gt;'.$title.'&lt;/'.$title_wrap.'&gt;';
}
</pre>
<p>There will be no title if the &#8220;<code>title</code>&#8221; attribute is not specified. There will be a title with the <code>&lt;h3&gt;</code> tag if the &#8220;<code>title_wrap</code>&#8221; attribute is not specified. You should change the default of the attribute to something else (like <code>&lt;h4&gt;</code>) if you use something else as subheadings.</p>
<p>Let&#8217;s get to the &#8220;display the future posts or not&#8221; part now:</p>
<pre name="code" class="php">
if ($future == 'on') {
	// Include the future posts if the &quot;future&quot; attribute is set to &quot;on&quot;
	$post_status = array('publish','future');
}
else {
	// Exclude the future posts if the &quot;future&quot; attribute is set to &quot;off&quot;
	$post_status = 'publish';
}
</pre>
<p>I strongly recommend that you leave the &#8220;<code>future</code>&#8221; attribute &#8220;<code>on</code>&#8221; but if you don&#8217;t want to list the titles of your future posts (not drafts), you can set it to &#8220;<code>off</code>&#8220;.</p>
<p>All right, we finished coding the attribute parts (except &#8220;<code>limit</code>&#8220;). We can now get to the part where we get the posts:</p>
<pre name="code" class="php">
if ($error == false) { /* We are going to close this later */
	$args = array(
		'tax_query' =&gt; $tax_query,
		'posts_per_page' =&gt; $limit,
		'orderby' =&gt; 'date',
		'order' =&gt; 'ASC',
		'post_status' =&gt; $post_status
	);
	$the_posts = get_posts($args);
</pre>
<ul>
<li>The &#8216;<code>tax_query</code>&#8216; argument is defined by the <code>$tax_query</code> variable which we created just a minute ago in the &#8220;find the proper taxonomy&#8221; part.</li>
<li>The &#8216;<code>posts_per_page</code>&#8216; argument is defined by the &#8220;<code>limit</code>&#8221; attribute of the shortcode.</li>
<li>The &#8216;<code>orderby</code>&#8216; and &#8216;<code>order</code>&#8216; arguments are defined to get the posts listed chronologically &ndash; the newest post will be at the bottom of the list.</li>
<li>The &#8216;<code>post_status</code>&#8216; argument is defined by the <code>$post_status</code> variable which we also created above, in the &#8220;display the future posts or not&#8221; part.</li>
</ul>
<p>Now we&#8217;re done with fetching the posts, we can put everything together and create the post list!</p>
<pre name="code" class="php">
	/* if there is more than one post with the specified &quot;series&quot; taxonomy, display the list. if there is just one post with the specified taxonomy, there is no need to list the only post! */
	if (count($the_posts) &gt; 1) {
		// display the title first
		$output = $title_output;
		// create the list tag - notice the &quot;post-series-list&quot; class
		$output .= '&lt;'.$list.' class=&quot;post-series-list&quot;&gt;';
		// the loop to list the posts
		foreach ($the_posts as $post) {
			setup_postdata($post);
			if ($post-&gt;post_status == 'publish') {
				$output .= '&lt;li&gt;&lt;a href=&quot;'.get_permalink($post-&gt;ID).'&quot;&gt;'.get_the_title($post-&gt;ID).'&lt;/a&gt;&lt;/li&gt;';
			}
			else {
				/* we can not link the post if the post is not published yet! */
				$output .= '&lt;li&gt;Future post: '.get_the_title($post-&gt;ID).'&lt;/li&gt;';
			}
		}
		wp_reset_query();
		// close the list tag...
		$output .= '&lt;/'.$list.'&gt;';
		// ...and return the whole output!
		return $output;
	}
} /* Remember the "if" we did not close? <img src='http://wp.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  */
</pre>
<p>And the final code of our shortcode&#8217;s function will be like this:</p>
<pre name="code" class="php">
// The shortcode function of Post Series
function series_sc($atts) {
	extract(
		shortcode_atts(
			array(
				&quot;slug&quot; =&gt; '',
				&quot;id&quot; =&gt; '',
				&quot;title&quot; =&gt; '',
				&quot;title_wrap&quot; =&gt; 'h3',
				&quot;list&quot; =&gt; 'ul',
				&quot;limit&quot; =&gt; -1,
				&quot;future&quot; =&gt; 'on'
			),
			$atts
		)
	);
	if ($id) {
		// Use the &quot;id&quot; attribute if it exists
		$tax_query = array(array('taxonomy' =&gt; 'series', 'field' =&gt; 'id', 'terms' =&gt; $id));
	}
	elseif ($slug) {
		// Use the &quot;slug&quot; attribute if &quot;id&quot; does not exist
		$tax_query = array(array('taxonomy' =&gt; 'series', 'field' =&gt; 'slug', 'terms' =&gt; $slug));
	}
	else {
		// Use posts own Series tax if neither &quot;id&quot; nor &quot;slug&quot; exist
		$terms = get_the_terms($post-&gt;ID,'series');
		if ($terms &amp;&amp; !is_wp_error($terms)) {
			$tax_query = array(array('taxonomy' =&gt; 'series', 'field' =&gt; 'slug', 'terms' =&gt; $term[0]-&gt;slug));
		}
		else {
			$error = true;
		}
	}
	if ($title) {
		// Create the title if the &quot;title&quot; attribute exists
		$title_output = '&lt;'.$title_wrap.' class=&quot;post-series-title&quot;&gt;'.$title.'&lt;/'.$title_wrap.'&gt;';
	}
	if ($future == 'on') {
		// Include the future posts if the &quot;future&quot; attribute is set to &quot;on&quot;
		$post_status = array('publish','future');
	}
	else {
		// Exclude the future posts if the &quot;future&quot; attribute is set to &quot;off&quot;
		$post_status = 'publish';
	}
	if ($error == false) {
		$args = array(
			'tax_query' =&gt; $tax_query,
			'posts_per_page' =&gt; $limit,
			'orderby' =&gt; 'date',
			'order' =&gt; 'ASC',
			'post_status' =&gt; $post_status
		);
		$the_posts = get_posts($args);
		/* if there is more than one post with the specified &quot;series&quot; taxonomy, display the list. if there is just one post with the specified taxonomy, there is no need to list the only post! */
		if (count($the_posts) &gt; 1) {
			// display the title first
			$output = $title_output;
			// create the list tag - notice the &quot;post-series-list&quot; class
			$output .= '&lt;'.$list.' class=&quot;post-series-list&quot;&gt;';
			// the loop to list the posts
			foreach ($the_posts as $post) {
				setup_postdata($post);
				if ($post-&gt;post_status == 'publish') {
					$output .= '&lt;li&gt;&lt;a href=&quot;'.get_permalink($post-&gt;ID).'&quot;&gt;'.get_the_title($post-&gt;ID).'&lt;/a&gt;&lt;/li&gt;';
				}
				else {
					/* we can not link the post if the post is not published yet! */
					$output .= '&lt;li&gt;Future post: '.get_the_title($post-&gt;ID).'&lt;/li&gt;';
				}
			}
			wp_reset_query();
			// close the list tag...
			$output .= '&lt;/'.$list.'&gt;';
			// ...and return the whole output!
			return $output;
		}
	}
}
add_shortcode('series','series_sc');
</pre>
<hr />
<h2>Conclusion: Usage Examples</h2>
<p>Usage is pretty simple:</p>
<ol>
<li>Create your &#8220;series&#8221; from the Posts &raquo; Series page (as if you&#8217;re creating new categories),</li>
<li>Assign your posts to those &#8220;series&#8221; while writing (as if you&#8217;re choosing categories),</li>
<li>Use the <code>[series]</code> shortcode wherever you want!</li>
</ol>
<p>You probably noticed this: You can use the shortcode without any attributes &ndash; if you&#8217;re using it inside your series&#8217; posts:</p>
<p><code>[series]</code></p>
<p>But if you want to include series in pages or in a post which is not assigned to the series you&#8217;re including, you can use the &#8220;<code>slug</code>&#8221; or the &#8220;<code>id</code>&#8221; attributes:</p>
<p><code>[series slug="wordpress-themes"]</code><br /><code>[series id="146"]</code></p>
<p>Finally, you can limit the number of posts shown, you can set a title <em>and</em> its heading tag, you can change the list to an ordered (numbered) list and you can prevent the future posts to be shown:</p>
<p><code>[series title="More WordPress Theme Lists" title_wrap="h4" limit="5" list="ol" future="off"]</code></p>
<p>I don&#8217;t want to paste the 100+ lines of the full source code here (the tutorial is already long) but you can download the plugin we created <a href="http://wptutsplus.s3.amazonaws.com/273_Adding_Post_Series_Functionality_to_WordPress_With_Taxonomies/source/post-series.zip">from here</a>. Hope you like it!</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/plugins/adding-post-series-functionality-to-wordpress-with-taxonomies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a WordPress Network Widget</title>
		<link>http://wp.tutsplus.com/tutorials/plugins/creating-a-wordpress-network-widget/</link>
		<comments>http://wp.tutsplus.com/tutorials/plugins/creating-a-wordpress-network-widget/#comments</comments>
		<pubDate>Tue, 15 May 2012 10:24:14 +0000</pubDate>
		<dc:creator>Kailan Wyatt</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[widgets]]></category>
		<category><![CDATA[wordpress multisite]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25408</guid>
		<description><![CDATA[<p>In this tutorial, we are going to create a widget that will display sites from a WordPress Network of sites. This short tutorial will show you how simple it is, to create a widget and use it to navigate to different network sites.<span id="more-25408"></span></p>
<hr />
<h2><span>Step 1</span> Adding the Base for the Widget</h2>
<p>Assuming that you have already <a href="http://wp.tutsplus.com/tag/wordpress-multisite/">set up a Network of sites</a>, we will begin by creating a file <strong>mynetwork.php</strong>. Add the following code for the base to extend the WordPress Widget Class.</p>
<pre name="code" class="php">
/*
Plugin Name: Your Plugin Name Here
Plugin URI: http://yourpluginsite.com
Description: This displays your Blogs in your WP Network
Author: The Author Name Here
Version: 1.0.0
Author URI: http://theauthoraddress.com
*/
class MyNetwork_Widget extends WP_Widget {

	public function __construct() {
		// widget actual processes
	}

	public function form( $instance ) {
		// outputs the options form on admin
	}

	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
	}

	public function widget( $args, $instance ) {
		// outputs the content of the widget
	}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "mynetwork_widget" );' ) );
</pre>
<blockquote>
<p>
&#8220;The function add_action( &#8216;widgets_init&#8217;,&#8221;) is used to register our widget&#8221;
</p>
</blockquote>
<hr />
<h2><span>Step 2</span> Writing the Construct Function</h2>
<p>Now that we have the base of our widget, let&#8217;s start adding actual functionalities to it. We&#8217;ll start by adding a new object attribute called blogs. This attribute will be used as an array to hold the list of registered blogs on your site.</p>
<pre name="code" class="php">
class MyNetwork_Widget extends WP_Widget {
	public $blogs = null;
</pre>
<p>Now we will add some small snippets to our <code>__construct</code> function. First we will assign an array of blogs to the object attribute by using the WordPress function <code>get_blog_list</code>. Any time we plan to reference the array, we simply use <code>$this->blogs</code>.</p>
<pre name="code" class="php">
public function __construct() {
	$this->blogs = get_blog_list( 0, 'all' );
</pre>
<p>Lastly, we&#8217;ll call the parent constructor function and add some information about our widget. The function takes a <code>Base ID(string)</code>, <code>Name(string)</code>, <code>Options(array)</code> and <code>Control Options(array)</code>. This information will will be displayed in the widget panel.</p>
<pre name="code" class="php">
	parent::__construct(
		'mynetwork_widget', // Base ID
		'MyNetwork_Widget', // Name
		array(
			'description' => __( 'Display List of Blogs in Site Network', 'text_domain' )
		)
	);
}
</pre>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/272_Creating_a_WordPress_Network_Widget/construct.jpg" border="0" /></div>
<hr />
<h2><span>Step 3</span> Writing the Form Function</h2>
<p>In this step we will create the widget form found in the administrator. Our form will have an <code>Image Url</code> field for each blog on the site. The URL field will hold a thumbnail of the site being referenced.</p>
<h3>Looping Through Blogs</h3>
<p>The first thing we do is create a <code>foreach</code> loop that will loop through each site&#8217;s blogs created on your site. The loop does not include the blog name, so for this purpose we use the <code>get_blog_details</code> function. The function takes the blog id and can return <code>Blog Name</code>, <code>ID</code>, <code>Post Count</code>, <code>Path</code> and more. We will add the blog name above each URL field. If you you look closely, you will see that our <code>get_field_id</code> function uses the <code>blog_id</code>, this will make our name tag look like this <code>image-1</code> which will be important for us in our other functions.</p>
<pre name="code" class="php">
	public function form( $instance ) {
		// outputs the options form on admin
		foreach ($this-&gt;blogs AS $blog) {
			$image =  $instance['image-'.$blog['blog_id']];
			?&gt;
			&lt;p&gt;
				&lt;label&gt;&lt;strong&gt;&lt;?php echo get_blog_details($blog['blog_id'])-&gt;blogname; ?&gt;&lt;/strong&gt;&lt;/label&gt;&lt;br /&gt;
				&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'image-'.$blog['blog_id'] ); ?&gt;"&gt;&lt;?php _e( 'Image Url:' ); ?&gt;&lt;/label&gt;
				&lt;input class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'image-'.$blog['blog_id'] ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'image-'.$blog['blog_id']); ?&gt;" type="text" value="&lt;?php echo esc_attr( $image ); ?&gt;" /&gt;
			&lt;/p&gt;
			&lt;?php
		}
	}
</pre>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/272_Creating_a_WordPress_Network_Widget/form.jpg" border="0" /></div>
<hr />
<h2><span>Step 4</span> Writing the Update Function</h2>
<p>The Update Function will save the values entered in our widget form. First we make the variable <code>$instance</code> an array, then we make another loop of each blog. During the loop we will update the old <code>$instance</code> with <code>$new_instance</code> then we return the variable.</p>
<pre name="code" class="php">
	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
		$instance = array();
		foreach ($this->blogs AS $blog) {
			$instance['image-'.$blog['blog_id']] = strip_tags( $new_instance['image-'.$blog['blog_id']]);
		}
		return $instance;
	}
</pre>
<hr />
<h2><span>Step 5</span> Writing the Widget Function</h2>
<p>Finally, we have our widget function which will render HTML in our widget position. Within this function we add a foreach loop of our registered blogs and during each loop, we will define the <code>image</code>, <code>link</code> and <code>name</code> of the blog. We add an <code>if</code> statement to check to see if an <code>Image Url</code> was added in the widget panel, if no images were selected then the respectful blog will not be shown. This is one way that admin can choose to hide a blog from their widget list. Next we add some HTML, with an image of each blog wrapped in its <code>blog path</code> and at the bottom we call the blog&#8217;s name. We finish the function by closing all open tags.</p>
<pre name="code" class="php">
	public function widget( $args, $instance ) {
		// outputs the content of the widget
		foreach ($this-&gt;blogs AS $blog) {
			$image = $instance['image-'.$blog['blog_id']];
			$link = $blog['path'];
			$name = get_blog_details($blog['blog_id'])-&gt;blogname;
			if ($image) {
			?&gt;
				&lt;div&gt;
					&lt;div&gt;
						&lt;a href="&lt;?php echo $link; ?&gt;"&gt;&lt;img src="&lt;?php echo $image; ?&gt;" width="125" border="0" alt="&lt;?php echo $name; ?&gt;" /&gt;&lt;/a&gt;
					&lt;/div&gt;
					&lt;div&gt;&lt;h3&gt;&lt;?php echo $name; ?&gt;&lt;/h3&gt;&lt;/div&gt;
				&lt;/div&gt;
			&lt;?php
			}
		}
	}
</pre>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/272_Creating_a_WordPress_Network_Widget/widget.jpg" border="0" /></div>
<h3>Finished Code</h3>
<pre name="code" class="php">
&lt;?php
/**
 * @package MyNetwork
 * @version 1.0.0
 */
/*
Plugin Name: Your Plugin Name Here
Plugin URI: http://yourpluginsite.com
Description: This displays your Blogs in your WP Network
Author: The Author Name Here
Version: 1.0.0
Author URI: http://theauthoraddress.com
*/
?&gt;
&lt;?php
class MyNetwork_Widget extends WP_Widget {
	public $blogs = null;

	public function __construct() {
		$this-&gt;blogs = get_blog_list( 0, 'all' );
		parent::__construct(
			'mynetwork_widget', // Base ID
			'MyNetwork_Widget', // Name
			array(
				'description' =&gt; __( 'Display List of Blogs in Site Network', 'text_domain' )
			) // Args
		);
	}

	public function form( $instance ) {
		// outputs the options form on admin
		foreach ($this-&gt;blogs AS $blog) {
			$image =  $instance['image-'.$blog['blog_id']];
			?&gt;
			&lt;p&gt;
				&lt;label&gt;&lt;strong&gt;&lt;?php echo get_blog_details($blog['blog_id'])-&gt;blogname; ?&gt;&lt;/strong&gt;&lt;/label&gt;&lt;br /&gt;
				&lt;label for="&lt;?php echo $this-&gt;get_field_id( 'image-'.$blog['blog_id'] ); ?&gt;"&gt;&lt;?php _e( 'Image Url:' ); ?&gt;&lt;/label&gt;
				&lt;input class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'image-'.$blog['blog_id'] ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'image-'.$blog['blog_id']); ?&gt;" type="text" value="&lt;?php echo esc_attr( $image ); ?&gt;" /&gt;
			&lt;/p&gt;
			&lt;?php
		}
	}

	public function update( $new_instance, $old_instance ) {
		// processes widget options to be saved
		$instance = array();
		foreach ($this-&gt;blogs AS $blog) {
			$instance['image-'.$blog['blog_id']] = strip_tags( $new_instance['image-'.$blog['blog_id']]);
		}
		return $instance;
	}

	public function widget( $args, $instance ) {
		// outputs the content of the widget
		foreach ($this-&gt;blogs AS $blog) {
			$image = $instance['image-'.$blog['blog_id']];
			$link = $blog['path'];
			$name = get_blog_details($blog['blog_id'])-&gt;blogname;
			if ($image) {
				?&gt;
				&lt;div&gt;
					&lt;div&gt;
						&lt;a href="&lt;?php echo $link; ?&gt;"&gt;&lt;img src="&lt;?php echo $image; ?&gt;" width="125" border="0" alt="&lt;?php echo $name; ?&gt;" /&gt;&lt;/a&gt;
					&lt;/div&gt;
					&lt;div&gt;&lt;h3&gt;&lt;?php echo $name; ?&gt;&lt;/h3&gt;&lt;/div&gt;
				&lt;/div&gt;
				&lt;?php
			}
		}
	}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "mynetwork_widget" );' ) );
?&gt;
</pre>
<hr />
<h2>Conclusion</h2>
<p>The styling of the blog was not covered in this tutorial but one can style the divs into a horizontal display or add some jQuery effects to make them scroll, fade or jump. I hope you find this tutorial useful and you adapt some of the snippets into your own widget. A great idea would be a carousel of registered site blogs. Please leave your feedback below. Happy coding!</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/plugins/creating-a-wordpress-network-widget/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Understanding the Walker Class</title>
		<link>http://wp.tutsplus.com/tutorials/creative-coding/understanding-the-walker-class/</link>
		<comments>http://wp.tutsplus.com/tutorials/creative-coding/understanding-the-walker-class/#comments</comments>
		<pubDate>Mon, 14 May 2012 07:52:14 +0000</pubDate>
		<dc:creator>Stephen Harris</dc:creator>
				<category><![CDATA[Creative Coding]]></category>
		<category><![CDATA[walker class]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25401</guid>
		<description><![CDATA[<p>Menu items, pages and (hierarchical) taxonomies are all examples of data with a tree like structure: terms can have parents, children and siblings. Usually we would like to reflect this structure in the HTML markup. For displaying a menu, for instance, we want the HTML to be of a list of &#8216;top level&#8217; links, with nested lists of their children, which themselves contain nested lists of their children, and so on. This tutorial will guide you through a class WordPress provides which makes producing this mark-up extremely simple.<span id="more-25401"></span></p>
<hr />
<h2>What Is the Walker Class?</h2>
<p>The walker class is an abstract class designed to help traverse and display elements which have a hierarchical (or tree like) structure. It doesn&#8217;t actually &#8216;do&#8217; (in the sense of generating HTML) <em>anything</em>. It simply traces each branch of your tree: it has to be extended by other classes which tell it what to do for each element it comes across. WordPress provides its own extending classes, such as:</p>
<ul>
<li><a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/nav-menu-template.php#L10"><code>Walker_Nav_Menu</code></a> &ndash; for displaying the HTML for navigation menus</li>
<li><a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/post-template.php#L971"><code>Walker_Page</code></a> &ndash; for displaying a list of pages</li>
<li><a href="http://core.trac.wordpress.org/browser/trunk/wp-includes/category-template.php#L759"><code>Walker_Category</code></a> &ndash; for displaying a list of taxonomy terms.</li>
</ul>
<p>Each of these classes extend the Walker class by simply dictating what the class outputs at each element and level of the tree. In order to de-mystify this class we shall look at its main methods and a couple of examples of how to use it. The class itself can be found <a title="Walker Class" href="http://core.trac.wordpress.org/browser/trunk/wp-includes/class-wp-walker.php">here</a>.</p>
<hr />
<h2>Walking the Tree</h2>
<h3><code>Walk</code></h3>
<pre name="code" class="php">walk( $elements, $max_depth)</pre>
<p>The walker class gets kicked off with the walk method and it&#8217;s this method which returns the HTML once it&#8217;s been generated. It accepts two arguments:</p>
<ol>
<li>An array of elements that we wish to display, which will have some sort of parent-child relationship</li>
<li><code>$max_depth</code> &ndash; sets how many generations we explore</li>
<li>Ok 3&#8230; If you scratch the surface of this method you&#8217;ll find you can actually pass extra arguments which get gathered into an array: <code>$args</code>. This is then passed to other methods in the class</li>
</ol>
<p>The walk method singles out the &#8216;top level&#8217; elements &ndash; those without parents &ndash; and places them in one array. The rest, the children, are placed in a second array where the key is the ID of its parent (it&#8217;s a two dimensional array as one parent can have multiple children):</p>
<pre name="code" class="php">
$children_elements = array(
	'1' =&gt; array() //Array of elements corresponding to children of 1,
	'4' =&gt; array() //Array of elements corresponding to children of 4
);
</pre>
<p>It then loops through each of the parent elements in turn and applies the method <code>display_element</code>.</p>
<h3><code>Display_Element</code></h3>
<pre name="code" class="php">display_element( $element, &amp;$children_elements, $max_depth, $depth=0, $args, &amp;$output )</pre>
<p>As the name suggests <code>display_element</code> is responsible for displaying an element in our tree. In fact, it calls several functions to do this. These functions are deliberately left blank in the Walker class &ndash; and it&#8217;s these which are altered in the extending classes, as they determine the actual HTML returned. These include:</p>
<ul>
<li><code>start_lvl</code> &ndash; a function to return the HTML for the start of a new level. In the case of lists, this would be the start of a new &#8216;sub-list&#8217;, and so would be responsible for returning the <code>&lt;ul&gt;</code> tag</li>
<li><code>end_lvl</code> &ndash; called when we have finished a level. In the navigation menu example, this function is responsible for ending the sub-list with a closing list tag <code>&lt;/ul&gt;</code></li>
<li><code>start_el</code> &ndash; the function responsible for displaying the current element we are on. In the case of menus, this means the <code>&lt;li&gt;</code> tag and the item&#8217;s link.</li>
<li><code>end_el</code> &ndash; the function called after an element and all it&#8217;s children have been displayed. For our menu example this means returning a closing <code>&lt;/li&gt;</code> tag.</li>
</ul>
<p>So what does <code>display_element</code> actually do? It&#8217;s actually where all the magic of the Walker class takes place. First lets take a look at what arguments it&#8217;s given:</p>
<ul>
<li><code>$element</code> &ndash; this is the element we are currently at on our tree</li>
<li><code>$children_elements</code> &ndash; an array of <em>all</em> child elements (not just children of the element referred to above). This is the second array formed in the <code>walk</code> method and the keys are the IDs of the parent.</li>
<li><code>$max_depth</code> &ndash; how far down we are allowed to explore</li>
<li><code>$depth</code> &ndash; how far down we currently are</li>
<li><code>$args</code> &ndash; optional arguments (mentioned earlier)</li>
<li><code>$output</code> &ndash; The HTML thus far. This is added to as we explore more of the tree.</li>
</ul>
<p> The <code>display_element</code> method first calls <code>start_el</code> which is responsible for displaying the element. Exactly how it does that depends on the context. For a drop-down menu it may be <code>&lt;select&gt; Current Item</code> or for a navigation menu it may <code>&lt;li&gt; Current Item</code>. Notice that there is no closing tag yet. If this element has children, we need to display them first so to that they are nested inside this item&#8230; </p>
<p>So next it checks if the current element we are on has any children and that we have not reached the maximum depth. If so, we explore each of the children in turn, by calling <code>display_element</code> for each of them (with the depth argument incremented by one). In this way the <code>display_element</code> recursively calls itself until we reach the bottom.</p>
<p>Suppose we have reached the &#8216;bottom&#8217; (an element with no children or the maximum depth), then it calls <code>end_el</code> which adds the closing tag. There the current instance of <code>display_element</code> finishes and we move back up to the parent who applies <code>display_element</code> to the next child, until we&#8217;ve processed each of its children. When the parent has no more children left we move back up the tree, and so on until every branch is explored. Confused? He&#8217;s a diagram which I hope will clarify things: </p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/271_Understanding_the_Walker_Class/wordpress-walker-class-diagram.png" border="0" /></div>
<hr />
<h2>Using the Walker Class: A Simple Example</h2>
<p>Using the Walker class makes displaying custom hierarchal data very simple. Suppose you have an array of objects, with &#8216;<code>label</code>&#8216;, &#8216;<code>parent_id</code>&#8216; and &#8216;<code>object_id</code>&#8216; properties that you wish to display a list of. This can now be easily be accomplished with a very simple class:</p>
<p><em><strong>Note:</strong> The extending class is responsible for setting where to find an element&#8217;s ID and that of its parent.</em></p>
<pre name="code" class="php">
class Walker_Simple_Example extends Walker {

	// Set the properties of the element which give the ID of the current item and its parent
	var $db_fields = array( 'parent' =&gt; 'parent_id', 'id' =&gt; 'object_id' );

	// Displays start of a level. E.g '&lt;ul&gt;'
	// @see Walker::start_lvl()
	function start_lvl(&amp;$output, $depth=0, $args=array()) {
		$output .= "\n&lt;ul&gt;\n";
	}

	// Displays end of a level. E.g '&lt;/ul&gt;'
	// @see Walker::end_lvl()
	function end_lvl(&amp;$output, $depth=0, $args=array()) {
		$output .= "&lt;/ul&gt;\n";
	}

	// Displays start of an element. E.g '&lt;li&gt; Item Name'
	// @see Walker::start_el()
	function start_el(&amp;$output, $item, $depth=0, $args=array()) {
		$output. = "&lt;li&gt;".esc_attr($item-&gt;label);
	}

	// Displays end of an element. E.g '&lt;/li&gt;'
	// @see Walker::end_el()
	function end_el(&amp;$output, $item, $depth=0, $args=array()) {
		$output .= "&lt;/li&gt;\n";
	}
}
$elements=array(); // Array of elements
echo Walker_Simple_Example::walk($elements);
</pre>
<hr />
<h2>Using the Walker Class: Advanced Example</h2>
<p>You can extend the walker classes to change what content is displayed, alter the HTML generated or even prevent certain branches from being shown. Functions such as:</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_nav_menu"><code>wp_nav_menu</code></a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_list_pages"><code>wp_list_pages</code></a></li>
<li><a href="http://codex.wordpress.org/Template_Tags/wp_list_categories"><code>wp_list_categories</code></a></li>
</ul>
<p>Provide an option to specify your own custom Walker class &ndash; allowing you to alter their appearance with relative ease by specifying your own custom walker class. In many instances it is actually easier to extend an appropriate walker extension, rather than the Walker class itself.</p>
<p>Suppose you want to have a secondary (sub) menu that is related to your primary menu. This may take the form of links that sit just below your primary menu or in a side-bar which show only the &#8216;descendant&#8217; menu items of the current &#8216;top-level page&#8217;. As an example from the diagram above, if we&#8217;re on the &#8216;Archive&#8217;, &#8216;Author&#8217;, or &#8216;News&#8217; sub pages, we would like to show all of the links below &#8216;Archive&#8217;. Since <code>Walker_Nav_Menu</code> does most of what we want, we shall extend that class rather than the Walker class. This saves us a lot of effort, since the <code>Walker_Nav_Menu</code> adds the appropriate classes (&#8216;<code>current</code>&#8216;, &#8216;<code>current-ancestor</code>&#8216; etc) to the relevant links. We shall extend the <code>Walker_Nav_Menu</code> walker class to alter the logic slightly, and prevent it from displaying any top-level links or any of the descendants of  the &#8216;non-root&#8217; pages.</p>
<h3>Some Ground Work: Theme Locations</h3>
<p>First of all, in your template files, we will use the <code>wp_nav_menu()</code> function twice, pointing to the same <em>theme location</em> (I shall call it &#8216;<code>primary</code>&#8216;). If you don&#8217;t have a theme location registered already you should <a href="http://wp.tutsplus.com/tutorials/wordpress-theme-development-training-wheels-lesson-3/">read this article</a>. Whichever theme location you are using, you should save a menu to that location. We shall display this menu twice. First, wherever you want your &#8216;top-level&#8217; menu to appear:</p>
<pre name="code" class="php">wp_nav_menu( array('theme_location'=&gt;'primary','depth' =&gt; 1) );</pre>
<p>Then again, with a custom walker, to display only the (relevant) child pages.</p>
<pre name="code" class="php"> wp_nav_menu( array('theme_location'=&gt;'primary','walker' =&gt; new SH_Child_Only_Walker(),'depth' =&gt; 0) );</pre>
<h3>Extending the Walker</h3>
<p>First of all we don&#8217;t want to display top-level parents. Recall that the function responsible for the opening <code>&lt;li&gt;</code> tag and the link is <code>start_el</code> and the function responsible for the closing <code>&lt;/li&gt;</code> tag is <code>end_el</code>. We simply check if we are at the parent level. If we are, we don&#8217;t do anything. Otherwise, we continue &#8216;as normal&#8217; and call the function from the <code>Walker_Nav_Menu</code> class.</p>
<pre name="code" class="php">
// Don't print top-level elements
function start_el(&amp;$output, $item, $depth=0, $args=array()) {
	if( 0 == $depth )
		return;
	parent::start_el(&amp;$output, $item, $depth, $args);
}

function end_el(&amp;$output, $item, $depth=0, $args=array()) {
	if( 0 == $depth )
		return;
	parent::end_el(&amp;$output, $item, $depth, $args);
}
</pre>
<p>We extend the <code>display_element</code>. This function is responsible for traveling down the branches. We want to stop it in its tracks if we are at the top-level and not on the current root link. To check if the branch we are on is &#8216;current&#8217;, we check if the item has any of the following classes: &#8216;<code>current-menu-item</code>&#8216;, &#8216;<code>current-menu-parent</code>&#8216;, &#8216;<code>current-menu-ancestor</code>&#8216;.</p>
<pre name="code" class="php">
// Only follow down one branch
function display_element( $element, &amp;$children_elements, $max_depth, $depth=0, $args, &amp;$output ) {

	// Check if element as a 'current element' class
	$current_element_markers = array( 'current-menu-item', 'current-menu-parent', 'current-menu-ancestor' );
	$current_class = array_intersect( $current_element_markers, $element-&gt;classes );

	// If element has a 'current' class, it is an ancestor of the current element
	$ancestor_of_current = !empty($current_class);

	// If this is a top-level link and not the current, or ancestor of the current menu item - stop here.
	if ( 0 == $depth &amp;&amp; !$ancestor_of_current)
		return;

	parent::display_element( $element, &amp;$children_elements, $max_depth, $depth, $args, &amp;$output );
}
</pre>
<p>We now extend the <code>start_lvl</code> and <code>end_lvl</code> functions. These are responsible for outputting the HTML that wraps a level (in this case the  <code>&lt;ul&gt;</code> tags). If we are on the top level we don&#8217;t want to display these tags (after all the contents will not be shown).</p>
<pre name="code" class="php">
// Don't wrap the top level
function start_lvl(&amp;$output, $depth=0, $args=array()) {
	if( 0 == $depth )
		return;
	parent::start_lvl(&amp;$output, $depth, $args);
}

function end_lvl(&amp;$output, $depth=0, $args=array()) {
	if( 0 == $depth )
		return;
	parent::end_lvl(&amp;$output, $depth, $args);
}
</pre>
<p>That class in full:</p>
<pre name="code" class="php">
class SH_Child_Only_Walker extends Walker_Nav_Menu {

	// Don't start the top level
	function start_lvl(&amp;$output, $depth=0, $args=array()) {
		if( 0 == $depth )
			return;
		parent::start_lvl(&amp;$output, $depth,$args);
	}

	// Don't end the top level
	function end_lvl(&amp;$output, $depth=0, $args=array()) {
		if( 0 == $depth )
			return;
		parent::end_lvl(&amp;$output, $depth,$args);
	}

	// Don't print top-level elements
	function start_el(&amp;$output, $item, $depth=0, $args=array()) {
		if( 0 == $depth )
			return;
		parent::start_el(&amp;$output, $item, $depth, $args);
	}

	function end_el(&amp;$output, $item, $depth=0, $args=array()) {
		if( 0 == $depth )
			return;
		parent::end_el(&amp;$output, $item, $depth, $args);
	}

	// Only follow down one branch
	function display_element( $element, &amp;$children_elements, $max_depth, $depth=0, $args, &amp;$output ) {

		// Check if element as a 'current element' class
		$current_element_markers = array( 'current-menu-item', 'current-menu-parent', 'current-menu-ancestor' );
		$current_class = array_intersect( $current_element_markers, $element-&gt;classes );

		// If element has a 'current' class, it is an ancestor of the current element
		$ancestor_of_current = !empty($current_class);

		// If this is a top-level link and not the current, or ancestor of the current menu item - stop here.
		if ( 0 == $depth &amp;&amp; !$ancestor_of_current)
			return

		parent::display_element( $element, &amp;$children_elements, $max_depth, $depth, $args, &amp;$output );
	}
}
</pre>
<p>Once you understand how the walker class works you can extend it (or WordPress&#8217; existing extensions) to alter how your hierarchal data is displayed. For instance you can:</p>
<ul>
<li>Include descriptions with menu links or category descriptions.</li>
<li>Exclude whole branches of a menu for logged-out users.</li>
<li>Include post meta in your list of pages.</li>
</ul>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/creative-coding/understanding-the-walker-class/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Connecting a WordPress Domain to Google Apps</title>
		<link>http://wp.tutsplus.com/tutorials/hosting/connecting-a-wordpress-domain-to-google-apps/</link>
		<comments>http://wp.tutsplus.com/tutorials/hosting/connecting-a-wordpress-domain-to-google-apps/#comments</comments>
		<pubDate>Sun, 13 May 2012 09:06:13 +0000</pubDate>
		<dc:creator>Austin Gunter</dc:creator>
				<category><![CDATA[Hosting]]></category>
		<category><![CDATA[emails]]></category>
		<category><![CDATA[Google Apps]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25386</guid>
		<description><![CDATA[<p>At WP Engine, we are often asked for email hosting recommendations. Unless it’s an enterprise client with hundreds or thousands of accounts, we recommend Google Apps for email. Gmail has done email so well that it doesn’t make sense to get email anywhere else, especially when gmail is free.</p>
<p>This tutorial will help you set up Gmail for a unique domain name for your business, blog, or whatever you’ve built on WordPress: yourname@yourdomain.com.<span id="more-25386"></span></p>
<hr />
<h2><span>Step 1</span> Specify the Domain for Google</h2>
<p>To start out, visit the Google Apps c-panel at https://www.google.com/a/cpanel/standard/new3, and specify the domain you’d like to use for your email address. Type your domain into the field, and hit submit.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/create-your-new.png" border="0" /></div>
<p>From here, you can fill out the rest of the form with information about your business and accept the terms and conditions. This is fairly straightforward information, including a physical address, and business size.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/google-accounts.png" border="0" /></div>
<p><em><strong>Note:</strong> Once you’ve submitted this page, if you’re signed into your normal Gmail account, you will be prompted to either cancel the request or to switch Gmail accounts using the Google Control Panel.</em></p>
<p>You want to switch accounts. Do <em>not</em> cancel the request. Once you’ve accepted it, you’ll go right on to Step 2.</p>
<hr />
<h2><span>Step 2</span> Express Install</h2>
<p>First, you need to choose whether you want to do the Express Install, ideal for on person installs, or the Custom Install, where you can test out various apps for a few different users.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/express-install.png" border="0" /></div>
<p>For our purposes, we’ll go ahead and do the Express Install. It takes about 30 minutes, and involves verifying domain ownership, setting up users and groups, and mobile access.</p>
<hr />
<h2><span>Step 3</span> Verifying Domain Ownership</h2>
<p><em>This is the longest part of the tutorial, so bear with me and we’ll get through it.</em></p>
<p>In order to prove that you actually own the domain and have legal rights to send and receive email from the domain, you have to verify your domain. This prevents mischievous folks from registering email addresses like <a href="mailto:yourname@cnn.com">yourname@cnn.com</a>, or <a href="mailto:thepresident@whitehouse.gov">thepresident@whitehouse.gov</a>.</p>
<p>You can select various ways to prove ownership, including using FTP to upload an HTML file to your site, adding tags to the head of your site, and the way that we’re going to do it: using a plugin!</p>
<p>Before this plugin existed, it was cumbersome to validate your domain, because none of the above methods are straightforward for the average user. Plugins are part of what make WordPress so great for so many people.</p>
<p><em><strong>Note:</strong> You don’t have to do anything else inside Google Apps at this point.</em></p>
<p>Log in to your WordPress Dashboard, and select Plugins -&gt; Add New.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/add-new-plugin.png" border="0" /></div>
<p>Then search for “Google Site Verification Plugin. Click “install now” to install the plugin to your site.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/google-site-verification.png" border="0" /></div>
<p>You’ll go to a status screen that tells you the plugin has been successfully installed. Now you have to activate the plugin. Select “activate plugin,” and you’ll be taken back to your installed plugins list.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/downloading-install-package.png" border="0" /></div>
<p>In order to verify your domain, find the google site verification plugin, and click “Verify.”</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/google-site-verification-plugin.png" border="0" /></div>
<p>You’ll arrive at the site verification start dialogue. Click “Start Verification.”</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/start-verification.png" border="0" /></div>
<p>You’ll be taken to a Google page that explains a third party, WordPress, is requesting permission to access your account. Select continue.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/third-party-app.png" border="0" /></div>
<p><em><strong>Note:</strong> it doesn’t matter if you’re signed into the email account you wish to verify. Any Gmail account will suffice to validate the domain.</em></p>
<p>Then Google will ask you if you want to grant access to the plugin. Select “Grant Access.”</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/grant-access.png" border="0" /></div>
<p>Awesome! You’re back in your WordPress dashboard, and should be looking at the screen telling you that your domain has been verified!</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/269_Connecting_a_WordPress_Domain_to_Google_Apps/google-site-verification.png" border="0" /></div>
<p>You now have access to webmaster tools for your site, and can manage a host of Google Apps from this dashboard, including analytics, and Google Docs.</p>
<hr />
<h2>Summary</h2>
<p>From here, it’s a simple matter of signing into your new gmail account and setting up the account the way you want it. I have all my email sent to the same inbox, but you may want to separate them out, depending on how you organize your work and your life.</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/hosting/connecting-a-wordpress-domain-to-google-apps/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Conditionally Including JS and CSS With get_current_screen</title>
		<link>http://wp.tutsplus.com/articles/tips-articles/quick-tip-conditionally-including-js-and-css-with-get_current_screen/</link>
		<comments>http://wp.tutsplus.com/articles/tips-articles/quick-tip-conditionally-including-js-and-css-with-get_current_screen/#comments</comments>
		<pubDate>Sat, 12 May 2012 09:56:15 +0000</pubDate>
		<dc:creator>Gordan Orlic</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[quick tip]]></category>
		<category><![CDATA[wp_enqueue_script]]></category>
		<category><![CDATA[wp_enqueue_style]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25378</guid>
		<description><![CDATA[<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>
<blockquote>
<p>
&#8220;Never include CSS or JS files on all admin pages. It will cause conflicts with other plugins.&#8221;
</p>
</blockquote>
<hr />
<h2>There&#8217;s a WordPress Function for Everything</h2>
<p>Since almost all admin pages have a unique URL it&#8217;s really not difficult to detect when a certain page is loaded and then (and only then) include JS and CSS files we need. We can use <code>$_SERVER['REQUEST_URI']</code>, or in many cases, the <code>$_GET['action']</code> variable. However there&#8217;s a much easier, cleaner and more standardized way of doing that. Say hello to the <a href="http://codex.wordpress.org/Function_Reference/get_current_screen"><code>get_current_screen</code></a> function.</p>
<h3>Things to know about the <code>get_current_screen</code> function:</h3>
<ul>
<li>It was introduced in WordPress v3.1, so if you try to use it in older versions you&#8217;ll get a &#8220;call to undefined function&#8221; error. Using the <code>function_exists</code> function to check for it is a good idea if you want to provide an alternative.</li>
<li>It&#8217;s not available in the <code>admin_init</code> or <code>init</code> hooks because it gets initialized after those hooks are called.</li>
<li>The function returns a <a href="http://codex.wordpress.org/Class_Reference/WP_Screen"><code>WP_Screen</code></a> object with a lot of info but you&#8217;ll mainly be interested in the <code>id</code> object property.</li>
<li>It&#8217;s not available on the front-end (because it serves no purpose there).</li>
</ul>
<hr />
<h2>A Few Lines of Code Make All the Difference</h2>
<p>Let&#8217;s assume your plugin has an options page under the Settings menu which you created with:</p>
<pre name="code" class="php">add_options_page('My Plugin', 'My Plugin', 'manage_options', 'my_plugin', 'my_plugin_options');</pre>
<p>You need some extra CSS and JavaScript on that page so you add this code as well:</p>
<pre name="code" class="php">
// Bad code below! Don't copy/paste!
add_action('admin_enqueue_scripts', 'my_plugin_scripts');

function my_plugin_scripts() {
	wp_enqueue_style('farbtastic');
	wp_enqueue_script('farbtastic');
}
</pre>
<p>That&#8217;s bad! Don&#8217;t do that! The snippet above will include CSS and JS for Farbtastic color picker on every single admin page. If other plugins want to get rid of your includes on their pages they have to use <code>wp_dequeue_*</code> functions to dequeue them. That&#8217;s really unnecessary and rude of us because we can write better code!</p>
<hr />
<pre name="code" class="php">
add_action('admin_enqueue_scripts', 'my_plugin_scripts');

function my_plugin_scripts() {
	// Include JS/CSS only if we're on our options page
	if (is_my_plugin_screen()) {
		wp_enqueue_style('farbtastic');
		wp_enqueue_script('farbtastic');
	}
}

// Check if we're on our options page
function is_my_plugin_screen() {
	$screen = get_current_screen();
	if (is_object($screen) &amp;&amp; $screen-&gt;id == 'settings_page_my_plugin') {
		return true;
	} else {
		return false;
	}
}
</pre>
<hr />
<h2>It&#8217;s Really Easy</h2>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/268_Quick_Tip_Conditionally_Including_JS_and_CSS_With_get_current_screen/code.png" border="0" /></div>
<p>If you have a look at our improved code you can see we only added one <code>if</code> statement and a simple function &ndash; <code>is_my_plugin_screen</code> which checks if we&#8217;re on our plugin&#8217;s options page. The variable <code>$screen</code> holds the <code>WP_Screen</code> object which has many properties but we&#8217;re only interested in the <code>id</code> one. That <code>id</code> consists of a prefix &#8220;<code>settings_page_</code>&#8220;, which is the same for all settings pages, and a string &#8220;<code>my_plugin</code>&#8221; which is unique to our plugin because we defined it as the 4th parameter in the <code>add_options_page</code> function call.</p>
<p>The code is very simple and easily adaptable to any admin screen. To see what the id is of the current screen simply dump the content of <code>$screen</code> with:</p>
<pre name="code" class="php">echo '&lt;pre&gt;' . print_r(get_current_screen(), true) . '&lt;/pre&gt;';</pre>
<hr />
<h2>Things to take home:</h2>
<ul>
<li>Never include CSS or JS files on all admin pages; it will cause conflicts with other plugins.</li>
<li>Use <code>get_current_screen</code> after <code>init</code> to find out when your admin screen is visible and only then include additional files.</li>
<li>You can find a list of the core admin screen IDs in the Codex under <a href="http://codex.wordpress.org/Plugin_API/Admin_Screen_Reference">Admin Screen Reference</a>.</li>
<li>Never echo <code>&lt;script&gt;</code> or <code>&lt;style&gt;</code> tags; always use <code>wp_enqueue_*</code> functions.</li>
<li>Check the <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">Codex</a> to see if the script you need is included in WP core already.</li>
</ul>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/articles/tips-articles/quick-tip-conditionally-including-js-and-css-with-get_current_screen/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Which Tuts+ Site Should We Launch Next?</title>
		<link>http://wp.tutsplus.com/articles/news/which-tuts-site-should-we-launch-next/</link>
		<comments>http://wp.tutsplus.com/articles/news/which-tuts-site-should-we-launch-next/#comments</comments>
		<pubDate>Fri, 11 May 2012 09:12:13 +0000</pubDate>
		<dc:creator>David Appleyard</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Launch]]></category>
		<category><![CDATA[poll]]></category>
		<category><![CDATA[tuts]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25349</guid>
		<description><![CDATA[<p>We&#8217;re planning our next few Tuts+ sites, and would love your opinion and advice on which topics you think we should cover next! We&#8217;d be really grateful if you could take a minute to answer our quick poll and share your thoughts&#8230;<span id="more-25349"></span></p>
<hr />
<h2>Have Your Say</h2>
<div style="float:right; margin:0 0 0 20px;"><script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6211923.js"></script><br />
<noscript><a href="http://polldaddy.com/poll/6211923/">Wptuts+ Readers: Which Tuts+ Site Should We Launch Next?</a></noscript></div>
<p>We&#8217;ve been considering lots of different ideas for our next Tuts+ sites over the past few weeks, and wanted to also ask the opinion of our awesome community!</p>
<p>A selection of different concepts are included in the poll to the right, along with the option for you to submit your own ideas as well.</p>
<p>The important thing to note is that these are just ideas. Some of these are close to making our final cut, and others aren&#8217;t&#8230; We&#8217;d love to hear what you think, to help guide our decision.</p>
<p>Thanks for taking the time to offer your suggestion &ndash; I can&#8217;t wait to see what you have to say!</p>
<h3>Win a 6-Month Tuts+ Premium Membership</h3>
<p>Our poll will be running for the next couple of weeks, and we&#8217;ll be choosing one respondent at random to receive a six-month Tuts+ Premium membership!</p>
<p>To be entered into the giveaway, just leave a comment on this post to go into a bit more detail about your site suggestion. We&#8217;ll choose one comment at random to win the Tuts+ Premium membership when the poll ends.</p>
<p><strong>Best of luck!</strong></p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/articles/news/which-tuts-site-should-we-launch-next/feed/</wfw:commentRss>
		<slash:comments>94</slash:comments>
		</item>
		<item>
		<title>The Complete Guide To The WordPress Settings API, Part 8: Validation, Sanitisation, and Input II</title>
		<link>http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-8-validation-sanitisation-and-input-ii/</link>
		<comments>http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-8-validation-sanitisation-and-input-ii/#comments</comments>
		<pubDate>Thu, 10 May 2012 10:46:57 +0000</pubDate>
		<dc:creator>Tom McFarlin</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Theme Development]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[make a wordpress plugin]]></category>
		<category><![CDATA[plugin development in wordpress]]></category>
		<category><![CDATA[plugin development wordpress]]></category>
		<category><![CDATA[theme options page]]></category>
		<category><![CDATA[wordpress API]]></category>
		<category><![CDATA[wordpress options page]]></category>
		<category><![CDATA[wordpress plugin development]]></category>
		<category><![CDATA[wordpress settings]]></category>
		<category><![CDATA[wordpress themes options]]></category>
		<category><![CDATA[writing wordpress theme]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25361</guid>
		<description><![CDATA[<div class="seriesmeta">This entry is part 8 of 8 in the series <a href="http://wp.tutsplus.com/series/the-complete-guide-to-the-wordpress-settings-api/" class="series-692" title="The Complete Guide To The WordPress Settings API">The Complete Guide To The WordPress Settings API</a></div><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>In this article, we&#8217;re going to take a look at the final set of three options and how to hook them up to the front-end of the theme.<span id="more-25361"></span></p>
<p><strong>Before we get started:</strong> As with the last few, this article assumes that you&#8217;ve been following along with the rest of the series, have a working copy of the sample code installed, and are now relatively familiar with the Settings API and theme options. If you&#8217;re uncertain about any of the above, I highly recommend reading <a href="http://wp.tutsplus.com/series/the-complete-guide-to-the-wordpress-settings-api/">the rest of the articles</a> before diving into this post.</p>
<hr />
<h2>The Element Types, Continued</h2>
<h3>Checkbox</h3>
<p><a href="http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-4-on-theme-options/">Earlier in this series</a>, we added checkboxes. We could go back and revisit those, but let&#8217;s keep consistent with what we&#8217;ve done up to this point and introduce new options. Once we&#8217;re done, you can revisit the code we added at the beginning of the series for review.</p>
<p>First, let&#8217;s introduce the checkbox element to the <code>sandbox_theme_initialize_input_examples</code> function:</p>
<pre name="code" class="php">
add_settings_field(
	'Checkbox Element',
	'Checkbox Element',
	'sandbox_checkbox_element_callback',
	'sandbox_theme_input_examples',
	'input_examples_section'
);
</pre>
<p>Next, we need to go ahead and define the callback that we&#8217;ve specified above. Add the following function to your project:</p>
<pre name="code" class="php">
function sandbox_checkbox_element_callback() {

	$options = get_option( 'sandbox_theme_input_examples' );

	$html = '&lt;input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" /&gt;';
	$html .= '&lt;label for="checkbox_example"&gt;This is an example of a checkbox&lt;/label&gt;';

	echo $html;

} // end sandbox_checkbox_element_callback
</pre>
<p>We&#8217;ll be revisiting this function momentarily, but first notice that I&#8217;ve added a label element next to the checkbox. Checkboxes often have an element associated with them that also afford the ability to be clicked to trigger the checkbox. This makes it easier for users to toggle an option without having to click precisely in the checkbox.</p>
<p>To associate a label with a checkbox, you need to give the label&#8217;s <code>for</code> attribute the value of the <code>ID</code> attribute of the checkbox to which it is bound. Easy enough, right?</p>
<p>Now, refresh your options page and you should see the new element visible on your options page. But, for now, it doesn&#8217;t actually save or retrieve a value. First, let&#8217;s introduce a <code>value</code> attribute on the checkbox. This is somewhat arbitrary but it&#8217;s a common practice to give a checked element a value of &#8217;1.&#8217; Let&#8217;s do that now:</p>
<pre name="code" class="php">
$html = '&lt;input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1" /&gt;';
</pre>
<p>Next, let&#8217;s think through exactly what needs to happen when we save a value. Ideally:</p>
<ul>
<li>The user checks the element and saves the value</li>
<li>The page refreshes and the checkbox is checked</li>
<li>The user checks the element to disable it and saves the value</li>
<li>The page refreshes and the checkbox is not checked</li>
</ul>
<p>Relatively clear, right? Rather than reading the option, setting up a conditional, and checking for the presence or absence of a value, we can take advantage of WordPress&#8217; <code><a href="http://codex.wordpress.org/Function_Reference/checked">checked</a></code> function.</p>
<p>The function accepts three arguments, only the first of which is required:</p>
<ol>
<li>The first value is one of the values to compare</li>
<li>The second value to compare if the first value is not true</li>
<li>Whether or not to echo <code>check="checked"</code> to the browser</li>
</ol>
<p>So let&#8217;s update our code to use this function:</p>
<pre name="code" class="php">
$html = '&lt;input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1"' . checked( 1, $options['checkbox_example'], false ) . '/&gt;';
</pre>
<p>Refresh the page and check the option, save, and repeat.</p>
<p>If any of this looks a bit confusing, review the <a href="http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-7-validation-sanitisation-and-input-i/">previous article</a> where we cover the significances of each attribute on an option element.</p>
<p>Finally, let&#8217;s update the front end of the theme to check this option and render a string of text based on if the option has been checked. Recall that when we created the element, we gave it the value of &#8216;<code>1</code>&#8216;. This means that when the checkbox is checked and serialized, it will maintain a value of one. Simply put, we need to write a conditional that checks the value of the option and then renders text appropriately. In <strong>index.php</strong>, add this block of code:</p>
<pre name="code" class="html">
&lt;?php if( $input_examples['checkbox_example'] == '1' ) { ?&gt;
	&lt;p&gt;The checkbox has been checked.&lt;/p&gt;
&lt;?php } else { ?&gt;
	&lt;p&gt;The checkbox has not been checked.&lt;/p&gt;
&lt;?php } // end if ?&gt;
</pre>
<p>Now, go back to your settings page, toggle the checkbox, and refresh your page.</p>
<p>As mentioned at the beginning of this section, look back at the &#8216;Display Options&#8217; that we introduced earlier in this series and see if it&#8217;s much clearer now that we&#8217;ve examined how to introduce and manage checkbox elements.</p>
<h3>Radio Buttons</h3>
<p>Radio Buttons are elements that are useful in groups &ndash; after all, you&#8217;re never going to use a single radio button. The thing about radio elements is that they provide a way to allow users to choose one out of a mutually exclusive set of options.</p>
<p>For one reason or another, radio buttons are often a challenge for WordPress developers. Hopefully, we&#8217;ll make it as easy as possible to bring into our projects. As with the rest of the examples in this series, detail what we&#8217;re going to do:</p>
<ul>
<li>We want to introduce two options from which the user must select. We&#8217;ll be giving them very general labels.</li>
<li>The first option will be a radio element with the label &#8216;Option One&#8217; and will have the value of &#8217;1&#8242;.</li>
<li>The second option will be a radio element with the label &#8216;Option Two&#8217; and will have the value of &#8217;2&#8242;.</li>
</ul>
<p>Seems clear enough &ndash; let&#8217;s go ahead and add the field element to our options page:</p>
<pre name="code" class="php">
add_settings_field(
	'Radio Button Elements',
	'Radio Button Elements',
	'sandbox_radio_element_callback',
	'sandbox_theme_input_examples',
	'input_examples_section'
);
</pre>
<p>And let&#8217;s implement the radio element&#8217;s callback. First, we&#8217;ll specify the code, then we&#8217;ll review it:</p>
<pre name="code" class="php">
function sandbox_radio_element_callback() {

	$options = get_option( 'sandbox_theme_input_examples' );

	$html = '&lt;input type="radio" id="radio_example_one" name="sandbox_theme_input_examples[radio_example]" value="1"' . checked( 1, $options['radio_example'], false ) . '/&gt;';
	$html .= '&lt;label for="radio_example_one"&gt;Option One&lt;/label&gt;';

	$html .= '&lt;input type="radio" id="radio_example_two" name="sandbox_theme_input_examples[radio_example]" value="2"' . checked( 2, $options['radio_example'], false ) . '/&gt;';
	$html .= '&lt;label for="radio_example_two"&gt;Option Two&lt;/label&gt;';

	echo $html;

} // end sandbox_radio_element_callback
</pre>
<p>The first thing to notice when working with radio buttons is that they do <em>not</em> follow the typical examples of how to set the <code>ID</code> and <code>name</code> attributes. Notice that the <code>ID</code> attribute is unique and has no relationship to the rest of the attributes on the element. Also notice that each element&#8217;s associated label uses the <code>ID</code> for it&#8217;s <code>for</code> attribute. This binds the label to the radio button so that users can click on the label to select the radio element.</p>
<p>Next, notice that the <code>name</code> attributes are the same for each radio element but the <code>values</code> are different. This is what makes radio buttons mutually exclusive &ndash; each radio element needs to have the same <code>name</code> but the values must be unique.</p>
<p>Finally, we can set up a conditional on the homepage by checking the element&#8217;s value. In your theme&#8217;s <strong>functions.php</strong>, add the following block of code:</p>
<pre name="code" class="html">
&lt;?php if( $input_examples['radio_example'] == 1 ) { ?&gt;
	&lt;p&gt;The first option was selected.&lt;/p&gt;
&lt;?php } elseif( $input_examples['radio_example'] == 2 ) { ?&gt;
	&lt;p&gt;The second option was selected.&lt;/p&gt;
&lt;?php } // end if  ?&gt;
</pre>
<p>Load your theme&#8217;s homepage, toggle the options, and refresh. You should see the two sentences changing based on the value of the option elements.</p>
<h3>Select Box</h3>
<p>The last element that we&#8217;re going to review is the select element. This element gives users a drop-down menu of options from which to choose. Let&#8217;s plan out exactly what we need to introduce for this element:</p>
<ul>
<li>Define a select element. In our example, we&#8217;ll be treating it as three options for time.</li>
<li>We&#8217;ll give the options for &#8216;Never&#8217;, &#8216;Sometimes&#8217;, and &#8216;Always&#8217;.</li>
<li>We&#8217;ll populate a default option that will be set when the page loads.</li>
</ul>
<p>At this point in the series, this should be quite routine. Let&#8217;s get started &ndash; first, we&#8217;ll introduce the settings field:</p>
<pre name="code" class="php">
add_settings_field(
	'Select Element',
	'Select Element',
	'sandbox_select_element_callback',
	'sandbox_theme_input_examples',
	'input_examples_section'
);
</pre>
<p>Next, we&#8217;ll define the callback function. Review the code and then we&#8217;ll discuss it after the example:</p>
<pre name="code" class="php">
function sandbox_select_element_callback() {

	$options = get_option( 'sandbox_theme_input_examples' );

	$html = '&lt;select id="time_options" name="sandbox_theme_input_examples[time_options]"&gt;';
		$html .= '&lt;option value="default"&gt;Select a time option...&lt;/option&gt;';
		$html .= '&lt;option value="never"' . selected( $options['time_options'], 'never', false) . '&gt;Never&lt;/option&gt;';
		$html .= '&lt;option value="sometimes"' . selected( $options['time_options'], 'sometimes', false) . '&gt;Sometimes&lt;/option&gt;';
		$html .= '&lt;option value="always"' . selected( $options['time_options'], 'always', false) . '&gt;Always&lt;/option&gt;';
	$html .= '&lt;/select&gt;';

	echo $html;

} // end sandbox_radio_element_callback
</pre>
<p>First, refresh your options page to make sure the select element appears. Assuming that it does, let&#8217;s review the code above.</p>
<p>When defining the select element, we&#8217;ve given it an <code>ID</code> attribute and a <code>name</code> attribute much as we do with the rest of the elements that we&#8217;ve demonstrated. Next, each option has a unique value and text that corresponds to the value. Though you don&#8217;t have to do this, I&#8217;ve typically found it helpful when working in my projects. Finally, we&#8217;ve taken advantage of the <a href="http://codex.wordpress.org/Function_Reference/selected"><code>selected</code></a> helper that WordPress offers. This is much like the <a href="http://codex.wordpress.org/Function_Reference/checked"><code>checked</code></a> function that we&#8217;ve used in previous example except that it&#8217;s geared towards select options.</p>
<p>The last step will be to update the front end of the theme so that it checks the value of the select element after it has been saved. Add the following block of code to your <strong>index.php</strong>:</p>
<pre name="code" class="html">
&lt;?php if( $input_examples['time_options'] == 'never' ) { ?&gt;
	&lt;p&gt;Never display this. Somewhat ironic to even show this.&lt;/p&gt;
&lt;?php } elseif( $input_examples['time_options'] == 'sometimes' ) { ?&gt;
	&lt;p&gt;Sometimes display this.&lt;/p&gt;
&lt;?php } elseif( $input_examples['time_options'] == 'always' ) { ?&gt;
	&lt;p&gt;Always display this.&lt;/p&gt;
&lt;?php } // end if/else ?&gt;
</pre>
<p>Revisit the homepage of your theme, change up the options, and then refresh the page &ndash; you should notice the text update based on the option that you&#8217;ve selected.</p>
<hr />
<h2>Conclusion</h2>
<p>With that, we finally reach the end of <a href="http://wp.tutsplus.com/series/the-complete-guide-to-the-wordpress-settings-api/">this series</a>. The Settings API is a powerful feature of WordPress and provides us with the ability to implement well-designed, secure option pages, but it requires that we use it properly. Unfortunately, this is probably one of the most ignored features of the platform by many developers.</p>
<p>Ultimately, my goal was to walk developers through the API from the very beginning of understanding why it&#8217;s important, to settings, from menu pages, to tabbed navigation, and how to work with each of the element types.</p>
<p>Finally, remember that you can find the example code on <a href="https://github.com/tommcfarlin/WordPress-Settings-Sandbox">GitHub</a>. As you continue to work with the Settings API or find a feature that&#8217;s unclear, please contribute. I&#8217;d love for this series and the example code to continue to provide a source of education for the WordPress community.</p>
<hr />
<h2>Related Sources</h2>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/checked"><code>checked</code></a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/selected"><code>selected</code></a></li>
<li><a href="https://github.com/tommcfarlin/WordPress-Settings-Sandbox">WordPress Settings Sandbox</a></li>
</ul>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/the-complete-guide-to-the-wordpress-settings-api-part-8-validation-sanitisation-and-input-ii/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<series:name><![CDATA[The Complete Guide To The WordPress Settings API]]></series:name>
	</item>
		<item>
		<title>WordPress as a Knowledge Base</title>
		<link>http://wp.tutsplus.com/tutorials/business/wordpress-as-a-knowledge-base/</link>
		<comments>http://wp.tutsplus.com/tutorials/business/wordpress-as-a-knowledge-base/#comments</comments>
		<pubDate>Wed, 09 May 2012 10:22:46 +0000</pubDate>
		<dc:creator>Robert Călin</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Custom Post Types]]></category>
		<category><![CDATA[custom taxonomy]]></category>
		<category><![CDATA[knowledge base]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25337</guid>
		<description><![CDATA[<p>At work we previously used KBPublisher to manage our knowledge base. It costed money, it was hard to style, code is encrypted with ion cube and so on, basically very hard to maintain. WordPress can do the same things and even better.</p>
<p>This tutorial will show you how to use custom taxonomies for knowledge base sections and custom posts for knowledge base articles.<span id="more-25337"></span></p>
<hr />
<h2><span>Step 1</span> Administration</h2>
<p>Knowledge base sections and articles need to be managed. WordPress makes this easy to do with custom taxonomies and custom post types.</p>
<p>Just register the new taxonomy and post type. Add the following into <strong>functions.php</strong> from your theme.</p>
<blockquote><p><em>For more information on the ins and outs of this functionality, read our other <a href="http://wp.tutsplus.com/tag/custom-post-types/">custom post type</a> and <a href="http://wp.tutsplus.com/tag/custom-taxonomy/">custom taxonomy</a> articles.</em></p>
</blockquote>
<pre name="code" class="php">
function register_kb() {
	register_post_type( 'knowledgebase',
		array(
			'labels' =&gt; array(
				'name' =&gt; 'Knowledge Base',
				'menu_name' =&gt; 'Knowledge Base',
				'singular_name' =&gt; 'Article',
				'all_items' =&gt; 'All Articles'
			),
			'public' =&gt; true,
			'publicly_queryable' =&gt; true,
			'show_ui' =&gt; true,
			'show_in_menu' =&gt; true,
			'show_in_nav_menus' =&gt; true,
			'menu_position ' =&gt; 20,
			'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ),
			'hierarchical' =&gt; false,
			'taxonomies' =&gt; array( 'section' ),
			'has_archive' =&gt; true,
			'rewrite' =&gt; array( 'slug' =&gt; 'knowledgebase', 'hierarchical' =&gt; true, 'with_front' =&gt; false )
		)
	);

	register_taxonomy( 'section', array( 'knowledgebase' ),
		array(
			'labels' =&gt; array(
				'name' =&gt; 'Sections',
				'menu_name' =&gt; 'Sections',
				'singular_name' =&gt; 'Section',
				'all_items' =&gt; 'All Sections'
			),
			'public' =&gt; true,
			'hierarchical' =&gt; true,
			'show_ui' =&gt; true,
			'rewrite' =&gt; array( 'slug' =&gt; 'knowledgebase-section', 'hierarchical' =&gt; true, 'with_front' =&gt; false ),
		)
	);
}
add_action( 'init', 'register_kb' );

function kb_rewrite_rules( $wp_rewrite ) {
	$new_rules = array( 'knowledgebase/(.*)/(.*)' =&gt; 'index.php?post_type=knowledgebase&#038;section=' . $wp_rewrite->preg_index( 1 ) . '&#038;knowledgebase=' . $wp_rewrite->preg_index( 2 ) );
	$wp_rewrite-&gt;rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'kb_rewrite_rules' );
</pre>
<p>This will run after WordPress has finished loading but before any headers are sent, registering the post type and taxonomy. Also, it will add the rewrite rules for the permalinks of the taxonomy and post type.</p>
<p>The <code>register_post_type</code> registers the custom post type, this is used for the KB articles. The <code>register_taxonomy</code> registers the custom taxonomy, this is used for the KB sections. The articles won&#8217;t be hierarchical but the sections will be, so it gives the possibility to create a tree structure.</p>
<p>Also it would be nice to show the sections that an article is assigned to.</p>
<pre name="code" class="php">
function kb_columns( $defaults ) {
	$defaults['section'] = 'Sections';
	return $defaults;
}
add_filter( 'manage_knowledgebase_posts_columns', 'kb_columns' );

function kb_custom_column( $column_name, $post_id ) {
	$taxonomy = $column_name;
	$post_type = get_post_type( $post_id );
	$terms = get_the_terms( $post_id, $taxonomy );
	if ( !empty( $terms ) ) {
		foreach ( $terms as $term ) {
			$post_terms[] = "&lt;a href='edit.php?post_type={$post_type}&#038;{$taxonomy}={$term->slug}'&gt; " . esc_html(sanitize_term_field('name', $term->name, $term->term_id, $taxonomy, 'edit')) . '&lt;/a&gt;';
		}
		echo join( ', ', $post_terms );
	}
	else echo '&lt;i&gt;No terms.&lt;/i&gt;';
}
add_action( 'manage_knowledgebase_posts_custom_column', 'kb_custom_column', 10, 2 );
</pre>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/266_WordPress_as_a_Knowledge_Base/admin.jpg" border="0" /></div>
<p>Now add some sections and some articles so there is something to show.</p>
<hr />
<h2><span>Step 2</span> Showing the Sections</h2>
<p>Add the following into <strong>functions.php</strong> from your theme.</p>
<pre name="code" class="php">
function kb_sections( $sections = array(), $active_section = null ) {
	$taxonomy = 'section';
	$link_class = '';
	if ( empty( $sections ) ) {
		$link_class = 'root';
		$sections = get_terms( $taxonomy, array( 'parent' =&gt; 0, 'hide_empty' =&gt; 0 ) );
		$active_section = kb_active_section();
		echo '&lt;ul id="kb-sections" class="unstyled"&gt;';
	}
	if ( empty( $active_section ) ) {
		$active_section = '';
	}
	foreach ( $sections as $section ) {
		$toggle = '';
		$section_children = get_terms( $taxonomy, array( 'parent' =&gt; $section->term_id, 'hide_empty' =&gt; 0 ) );
		if ( !empty( $section_children ) &#038;&#038; $link_class != 'root' ) {
			$toggle = '&lt;i class="toggle"&gt;&lt;/i&gt;';
		}
		echo '&lt;li class="' . ( $section->term_id == $active_section ? 'active' : '' ) . '"&gt;';
		echo '&lt;a  href="' . get_term_link( $section, $taxonomy ) . '" class="' . $link_class . '" rel="' . $section->slug . '"&gt;' . $toggle . $section->name . '&lt;/a&gt;';

		if ( !empty( $section_children ) ) {
			echo '&lt;ul id="' . $section->slug . '" class="children"&gt;';
			kb_sections( $section_children, $active_section );
		}
		echo "&lt;/li&gt;";
	}
	echo "&lt;/ul&gt;";
}

function kb_active_section() {
	$taxonomy = 'section';
	$current_section = '';
	if ( is_single() ) {
		$sections = explode( '/', get_query_var( $taxonomy ) );
		$section_slug = end( $sections );
		if ( $section_slug != '' ) {
			$term = get_term_by( 'slug', $section_slug, $taxonomy );
		} else {
			$terms = wp_get_post_terms( get_the_ID(), $taxonomy );
			$term = $terms[0];
		}
		$current_section = $term->term_id;
	} else {
		$term = get_term_by( 'slug', get_query_var( $taxonomy ), get_query_var( 'taxonomy' ) );
		$current_section = $term->term_id;
	}
	return $current_section;
}
</pre>
<p>In the theme folder create a file called <strong>sidebar-sections.php</strong> where your <code>kb_sections</code> function will be called outputting an unordered and nested list of sections.</p>
<pre name="code" class="php">
&lt;?php kb_sections(); ?&gt;
</pre>
<p>Like this, the KB sections can be shown everywhere as desired by including the sidebar.</p>
<pre name="code" class="php">
&lt;?php get_sidebar( 'sections' ); ?&gt;
</pre>
<hr />
<h2><span>Step 3</span> Showing the Articles</h2>
<p>Add the following into <strong>functions.php</strong> from your theme.</p>
<pre name="code" class="php">
function kb_article_permalink( $article_id, $section_id ) {
	$taxonomy = 'section';
	$article = get_post( $article_id );
	$section = get_term( $section_id, $taxonomy );
	$section_ancestors = get_ancestors( $section->term_id, $taxonomy );
	krsort( $section_ancestors );
	$permalink = '&lt;a href="/knowledgebase/';
	foreach ($section_ancestors as $ancestor):
		$section_ancestor = get_term( $ancestor, $taxonomy );
		$permalink.= $section_ancestor->slug . '/';
	endforeach;
	$permalink.= $section->slug . '/' . $article->post_name . '/" &gt;' . $article->post_title . '&lt;/a&gt;';
	return $permalink;
}
</pre>
<p><strong>Note:</strong> this method is necessary because an article can be linked to multiple sections.</p>
<p>This will generate a hierarchical permalink structure.</p>
<p>Like: <code>/knowledgebase/section-slug/sub-section-slug/another-sub-section-slug/article-slug</code></p>
<p>In the theme folder then create these files: <strong>archive-knowledgebase.php</strong>, <strong>single-knowledgebase.php</strong>, <strong>content-knowledgebase.php</strong>, <strong>taxonomy-section.php</strong>.</p>
<p>In <strong>archive-knowledgebase.php</strong> add the following to show the sections and recent articles.</p>
<pre name="code" class="php">
&lt;?php
get_header();
get_sidebar( 'sections' );
while ( have_posts() ) : the_post();
	$terms = wp_get_post_terms( $post->ID, 'section' );
	$term = $terms[0];
	echo kb_article_permalink( $post->ID, $term->term_id );
endwhile;
get_footer();
?&gt;
</pre>
<p>In <strong>single-knowledgebase.php</strong> add the following.</p>
<pre name="code" class="php">
&lt;?php
get_header();
while ( have_posts() ) : the_post();
	get_template_part( 'content', 'knowledgebase' );
endwhile;
get_footer();
?&gt;
</pre>
<p>In <strong>content-knowledgebase.php</strong> add the following.</p>
<pre name="code" class="php">
&lt;?php
get_sidebar( 'sections' );
the_title();
the_content();
?&gt;
</pre>
<p>In <strong>taxonomy-section.php</strong> add the following to show a list of articles from a section.</p>
<pre name="code" class="php">
&lt;?php
global $wp_query;
$args = array_merge( $wp_query-&gt;query, array( 'posts_per_page' =&gt; 100 ) );
query_posts( $args );
$term = get_term_by( 'slug', get_query_var( 'term' ), 'section' );

get_header();
get_sidebar( 'sections' );
while ( have_posts() ) : the_post();
	echo kb_article_permalink( $post->ID, $term->term_id );
endwhile;
get_footer();
?&gt;
</pre>
<p>This can be structured and styled as desired.</p>
<hr />
<h2>Example</h2>
<p>A real life example of how this works and how it can be used: <a href="http://syneto.net/knowledgebase/" target="_blank">syneto.net</a></p>
<hr />
<h2>References</h2>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/add_action" target="_blank">add_action</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/register_post_type" target="_blank">register_post_type</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/register_taxonomy" target="_blank">register_taxonomy</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/add_filter" target="_blank">add_filter</a></li>
</ul>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/business/wordpress-as-a-knowledge-base/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>How to Create an Instant Image Gallery Plugin for WordPress</title>
		<link>http://wp.tutsplus.com/tutorials/plugins/how-to-create-an-instant-image-gallery-plugin-for-wordpress/</link>
		<comments>http://wp.tutsplus.com/tutorials/plugins/how-to-create-an-instant-image-gallery-plugin-for-wordpress/#comments</comments>
		<pubDate>Tue, 08 May 2012 09:51:34 +0000</pubDate>
		<dc:creator>John Sexton</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[plugin development]]></category>
		<category><![CDATA[wordpress gallery]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25321</guid>
		<description><![CDATA[<p>Learn how to create a simple, automatically generated image gallery plugin with thumbnail navigation for WordPress. The end result is a simple, attractive gallery with thumbnail navigation that is created <em>automatically</em> whenever you upload images to a post or page. No special settings, no options to configure, no hoops to jump through &ndash; it just works!<span id="more-25321"></span></p>
<hr />
<h2>Introduction</h2>
<p>Here is a preview of what we will be creating:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-complete.png" border="0" /></div>
<hr />
<h2>Using Instant Gallery for WordPress</h2>
<p>Before we get into the code, let&#8217;s take a quick look at how easy this gallery is to use. For those of you who just want to grab the code and use it, this section will show you how to do that.</p>
<p>For those that want to learn how to create this gallery, it is still good to get a sense of how it works before we start coding. So, let&#8217;s check it out!</p>
<h3>Instant Gallery: The 2-Minute Quick-Start Guide</h3>
<p>1. Start with a simple, blank Post or Page in WordPress. Hit the &#8220;Upload/Insert Media&#8221; button.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-howto-1.png" border="0" /></div>
<p>2. Next, upload some images to the Post or Page. Just drag and drop your images into the box.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-howto-2.png" border="0" /></div>
<p>3. When your images finish uploading, you&#8217;ll get a list of the images and their properties. You can drag and drop the images to re-order them on this screen. Instant Gallery respects the menu order that you set up in the WordPress media browser, so re-ordering the images here will re-order them on the gallery.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-howto-3.png" border="0" /></div>
<p>4. If you want to change any properties of the image, such as the Title, Caption or Description, then you can do that just like you normally would. In its current incarnation, Instant Gallery displays the image Title in the Gallery in between the main image and the thumbnails.</p>
<p>Why display the Title and not the other information? As you can see from the image, WordPress automatically fills out the Title of the image (using the image&#8217;s filename) as soon as you upload it. In keeping with the theme of making Instant Gallery as fast and easy to use as possible, I wanted to use the field that WordPress fills out automatically.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-howto-4.png" border="0" /></div>
<p>5. Finally, go back to your Post or Page and enter the <code>[instant_gallery]</code> shortcode in the content area. Hit save, and then go view your page. That&#8217;s it!</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-howto-5.png" border="0" /></div>
<p>So, that&#8217;s all there is to it. The purpose of Instant Gallery is to be the fastest, easiest way to create an image gallery by uploading images to a Post or Page in WordPress. If you think that will be useful to you, then go ahead and grab the files and have fun!</p>
<p>You&#8217;ll be creating beautifully simple WordPress image galleries in an instant!</p>
<p>Let&#8217;s take one more look at the finished product:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-complete.png" border="0" /></div>
<p>Now, if you are interested in learning how Instant Gallery was created, either to improve your skills as a coder, or to build upon Instant Gallery and make it better, then please keep reading!</p>
<hr />
<h2>Creating Instant Gallery</h2>
<p>As with most WordPress projects, we&#8217;ll be using HTML, CSS, PHP, and a little bit of JavaScript to accomplish our goal.</p>
<p>We will proceed in the following way:</p>
<ol>
<li><strong>HTML</strong> &ndash; Start with markup and fill it with static content</li>
<li><strong>WordPress / PHP</strong> &ndash; Dynamically populate our markup with content</li>
<li><strong>JavaScript</strong> &ndash; Apply the behavior to swap the images</li>
<li><strong>CSS</strong> &ndash; Complete the look and feel with CSS</li>
</ol>
<hr />
<h2><span>Step 1</span> The Markup</h2>
<p>The markup for our gallery is very simple. We just have a main containing element that encompasses the entire gallery (<code>#instant-gallery</code>), the primary content panel that contains our main image and its title (<code>#ig-main</code>), and then the thumbnail navigation area (<code>#ig-thumbs</code>).</p>
<pre name="code" class="html">
	&lt;div id="instant-gallery"&gt;

		&lt;!-- Main Display Area --&gt;
		&lt;div id="ig-main"&gt;

				&lt;!-- Main "Hero" Image --&gt;
				&lt;img id="ig-hero" src="http://placehold.it/600x300" /&gt;

				&lt;!-- Image Title --&gt;
				&lt;p id="ig-title"&gt;Title Goes Here&lt;/p&gt;

		&lt;!-- Close the main display area --&gt;
		&lt;/div&gt;

		&lt;!-- Open the Thumbnail navigation --&gt;
		&lt;ul id="ig-thumbs"&gt;

			&lt;!-- Now, for each of the thumbnail images, label the LI with an ID of the appropriate thumbnail number --&gt;
			&lt;li id="ig-thumb-1"&gt;

				&lt;!-- Output a thumbnail-sized version of the image --&gt;
				&lt;img class="thumb" src="http://placehold.it/150x150" /&gt;

			&lt;/li&gt;

			&lt;li id="ig-thumb-2"&gt;

				&lt;img class="thumb" src="http://placehold.it/150x150" /&gt;

			&lt;/li&gt;	

			&lt;li id="ig-thumb-3"&gt;

				&lt;img class="thumb" src="http://placehold.it/150x150" /&gt;

			&lt;/li&gt;

		&lt;!-- Close the thumbnail navigation list --&gt;
		&lt;/ul&gt;

	&lt;!-- Close the entire Gallery --&gt;
	&lt;/div&gt;
</pre>
<p>Our navigation is an unordered list and each list item contains a thumbnail image.</p>
<p>For simplicity, we will just use three placeholder thumbnails in the static HTML version. In the next section we will use PHP to dynamically generate as many thumbnails as we need.</p>
<p>If we check out our markup now, we&#8217;ll get something that looks like this (just showing two thumbnails to keep the image size down):</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-html-only.png" border="0" /></div>
<p>So, that&#8217;s the basic markup. Not too exciting, but simple, clean HTML is the foundation of just about everything we do on the web so it&#8217;s worth taking the time to get it right.</p>
<hr />
<h2><span>Step 2</span> The WordPress and PHP</h2>
<p>Now let&#8217;s get into the WordPress part of the tutorial. This may be the most exciting part for you Wptuts+ readers.</p>
<p>Let&#8217;s start by thinking conceptually about what we want to accomplish. The goal here is to have an image gallery automatically generated from any images that are uploaded to a given post or page.</p>
<p>In order to accomplish this, we need to know the following:</p>
<ul>
<li>What post or page are we on?</li>
<li>Are there any images attached to this page? If so, let&#8217;s get them and some information about them.</li>
<li>Then, for the first image, we want to display it in the gallery, along with a caption or descriptive text.</li>
<li>Then, for all of the images (including the first) images, we want to display them as thumbnails below the gallery.</li>
<li>The first image should also be highlighted to show that it is currently selected.</li>
</ul>
<p>With that general concept in mind, let&#8217;s take a look at the markup code from Step 1, now infused with the WordPress and PHP code we need to get the information we want. There is a fair amount going on here, so let&#8217;s break it down into smaller sections that correspond with the list above.</p>
<hr />
<h3>Step 2.1: Prepare the Query</h3>
<pre name="code" class="php">
//-------------------------------------------------
// Prepare the query
//-------------------------------------------------

	global $post;

	$args = array(
		'post_parent'    =&gt; $post-&gt;ID,			// For the current post
		'post_type'      =&gt; 'attachment',		// Get all post attachments
		'post_mime_type' =&gt; 'image',			// Only grab images
		'order'			 =&gt; 'ASC',				// List in ascending order
		'orderby'        =&gt; 'menu_order',		// List them in their menu order
		'numberposts'    =&gt; -1,					// Show all attachments
		'post_status'    =&gt; null,				// For any post status
	);
</pre>
<p>Here we are doing two main things:</p>
<p>First, we set up the global Post variable (<code>$post</code>) so we can have access to the relevant data about our post.</p>
<p>Second, we set up an array of arguments (<code>$args</code>) that define the kind of information we want to retrieve. Specifically, we need to get <em>images</em> that are <em>attached</em> to the <em>current post</em>. We&#8217;re also going to get <em>all of them</em>, and return them in the <em>same order they appear in the WordPress gallery</em>.</p>
<p>See the comments in the code snippet above to see which lines correspond to which parameters.</p>
<hr />
<h3>Step 2.2: Retrieve the Images</h3>
<pre name="code" class="php">
	// Retrieve the items that match our query; in this case, images attached to the current post.
	$attachments = get_posts($args);

		// If any images are attached to the current post, do the following:
		if ($attachments) {	

			// Initialize a counter so we can keep track of which image we are on.
			$count = 0;

			// Now we loop through all of the images that we found
			foreach ($attachments as $attachment) {
</pre>
<p>Here we are using the WordPress <a href="http://codex.wordpress.org/Template_Tags/get_posts" target="_blank">get_posts</a> function to retrieve the images that match our criteria as defined in <code>$args</code>. We are then storing the results in a variable called <code>$attachments</code>.</p>
<p>Next, we check to see if <code>$attachments</code> exists. If this variable is empty (as will be the case when your post or page has no images attached to it), then no further code will execute. If <code>$attachments</code> does have content, then we move on to the next step.</p>
<p>Next, we initialize a simple counter variable so we can keep track of which image we are on. We do this because there are certain things we&#8217;ll want to output only the first time through our loop (such as the main gallery markup). It also gives us a means to assign unique IDs to each thumbnail in the navigation if we would like.</p>
<p>Then we open the loop that will step through each of our images.</p>
<hr />
<h3>Step 2.3: Main Galley Area</h3>
<pre name="code" class="php">
//---------------------------------------------------------
// Output the main containers and first large image;
// This is stuff we will only want to output one time.
//---------------------------------------------------------
	if($count == 0) { ?&gt;

		&lt;!-- Whole Gallery container (includes thumbnails) --&gt;
		&lt;div id="instant-gallery"&gt;

			&lt;!-- Main Display Area --&gt;
			&lt;div id="ig-main"&gt;

					&lt;!-- Set the parameters for the image we are about to display. --&gt;
					&lt;?php $default_attr = array(
							'id' 	=&gt; "ig-hero",
							'alt'   =&gt; trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )),
							'title' =&gt; trim(strip_tags( $attachment-&gt;post_title )),
						);
					?&gt;

					&lt;!-- Display the first image attachment as the large image in the main gallery area --&gt;
					&lt;?php echo wp_get_attachment_image($attachment-&gt;ID, 'full', false, $default_attr); ?&gt;

					&lt;!-- Image Title --&gt;
					&lt;p id="ig-title"&gt;

					&lt;!-- Display the Title of this image below the image --&gt;
					&lt;?php echo $attachment-&gt;post_title; ?&gt;

					&lt;/p&gt;

			&lt;!-- Close the main display area --&gt;
			&lt;/div&gt;

			&lt;!-- Open the Thumbnail navigation --&gt;
			&lt;ul id="ig-thumbs"&gt;

	&lt;!-- End the block of stuff that we only do for the first image  --&gt;
	&lt;?php } ?&gt;
</pre>
<p>Here we use our counter variable to determine how many times we have been through our loop. If this is the first time, <code>$counter</code> will be equal to zero, and the block of code above will be executed. This code sets up the main structural elements of the gallery and populates the main image section with the first large image. This stuff only needs to happen once. For subsequent trips through the loop, <code>$counter</code> will be greater than zero and this block of code will be skipped.</p>
<p>Ok, so what&#8217;s actually going on in there? We&#8217;ve already looked at the HTML part in Step 1, so let&#8217;s focus on the PHP code that inhabits the main gallery area.</p>
<pre name="code" class="php">
	&lt;!-- Set the parameters for the image we are about to display. --&gt;
	&lt;?php $default_attr = array(
			'id' 	=&gt; "ig-hero",
			'alt'   =&gt; trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )),
			'title' =&gt; trim(strip_tags( $attachment-&gt;post_title )),
		);
	?&gt;

	&lt;!-- Display the first image attachment as the large image in the main gallery area --&gt;
	&lt;?php echo wp_get_attachment_image($attachment-&gt;ID, 'full', false, $default_attr); ?&gt;

	&lt;!-- Image Title --&gt;
	&lt;p id="ig-title"&gt;

	&lt;!-- Display the Title of this image below the main image --&gt;
	&lt;?php echo $attachment-&gt;post_title; ?&gt;

	&lt;/p&gt;
</pre>
<p>In the first section here, we define an array of parameters just like we did in Step 2.1. This time, however, instead of parameters for a query, we are setting parameters for a WordPress function called <a href="http://codex.wordpress.org/Function_Reference/wp_get_attachment_image" target="_blank"><code>wp_get_attachment_image</code></a>.</p>
<p>This function grabs the current attachment (our current image), returns the <em>full</em> size of the image (as opposed to a smaller size such as the Thumbnail; we&#8217;ll get into that later), and applies attributes to the image HTML tag that correspond to the arguments defined in the <code>$default_attr</code> array. The &#8220;alt&#8221; and &#8220;title&#8221; tags of the image are defined as you would expect, and the image is given an ID of <code>#ig-hero</code> so that we can easily target it with CSS.</p>
<p>Finally, we output image title again, this time as the Title which appears below the image. By default, WordPress sets the image Title to be equal to the <em>filename</em> of the uploaded image. So, when you use this technique, either (1) make sure the filenames of the images you upload are something you would like to have displayed on your slideshow, (2) edit the Title field of the images when you upload them, or (3) comment this part of the code out so that the title does not display in the slideshow at all.</p>
<hr />
<h3>Step 2.4: Thumbnail Navigation</h3>
<pre name="code" class="php">
	&lt;!-- Open the Thumbnail navigation --&gt;
	&lt;ul id="ig-thumbs"&gt;

		&lt;!-- End the block of stuff that we only do for the first image  --&gt;
		&lt;?php } ?&gt; 

			&lt;!-- Now, for each of the thumbnail images, label the LI with an ID of the appropriate thumbnail number --&gt;
			&lt;li id="ig-thumb-&lt;?php echo $count+1; ?&gt;"&gt;

				&lt;?php if ($count==0) {

					// If this is the first thumbnail, add a class of 'selected' to it so it will be highlighted
					$thumb_attr = array(
						'class' =&gt; "thumb selected",
						);

				} else {

					// For all other thumbnails, just add the basic class of 'thumb'
					$thumb_attr = array(
						'class' =&gt; "thumb",
						);

				} ?&gt;

				&lt;!-- Output a thumbnail-sized version of the image that has the attributes defined above --&gt;
				&lt;?php echo wp_get_attachment_image($attachment-&gt;ID, 'thumbnail', false, $thumb_attr); ?&gt;

			&lt;/li&gt;

				&lt;!-- Increment the counter so we can keep track of which thumbnail we are on --&gt;
				&lt;?php $count = $count + 1; 

			} ?&gt;

		&lt;!-- Close the thumbnail navigation list --&gt;
		&lt;/ul&gt;

	&lt;!-- Close the entire Gallery --&gt;
	&lt;/div&gt;

	&lt;?php }

	} ?&gt;
</pre>
<p>Now let&#8217;s take a closer look at the thumbnail navigation. At the top of this block of code we&#8217;ve repeated the opening of the <code>#ig-thumbs</code> list to help you orient yourself in the code. With that reference point in mind, let&#8217;s look at the actual list items themselves.</p>
<p>You&#8217;ll notice that we are using a little snippet of PHP to output the <code>$count</code> variable, plus one, to give each list item its own unique ID. This will give us just one more degree of control over the list items with CSS, should we want it. We use <code>$count+1</code> so that we don&#8217;t have to start at zero.</p>
<p>Inside the list item, there is a conditional statement that checks one more time which iteration of the loop we are on. As we have done a few times before, we are setting an array; however, this time it is an attribute for the thumbnail images. The difference here is that we are setting slightly different parameters for the array depending on if we are on the first trip through the loop or not.</p>
<p>We always give the thumbnail a class of &#8220;thumb&#8221;, but on the first trip through the loop we also give the first thumbnail a class of &#8220;selected&#8221;. This is something we will target with CSS later on in order to provide a consistent user experience.</p>
<p>Once the <code>$thumb_attr</code> attributes are set, we use <a href="http://codex.wordpress.org/Function_Reference/wp_get_attachment_image" target="_blank"><code>wp_get_attachment_image</code></a> again to output the image. The main thing to note this time is that we are grabbing the <em>thumbnail</em> version of the image instead of the <em>full</em> size of the image that we grabbed above.</p>
<p>Then, since we are at the end of our loop, we increment our counter and begin the loop again. Once we&#8217;ve exhausted all of our image attachments, we&#8217;ll hit the end of the loop. When this happens, we close the unordered list, then the whole gallery container, and then our PHP conditional statements.</p>
<hr />
<h3>Step 2.5: Add the Shortcode</h3>
<p>It&#8217;s great have coded up our image gallery, but it is even better if we can <em>display</em> our image gallery! At this point, we still don&#8217;t have any way to actually show the output on a WordPress Post or Page. We&#8217;re going to fix that right now, and fortunately this step is easy!</p>
<pre name="code" class="php">
	//-------------------------------------------------
	// Create the Shortcode for Instant Gallery
	//-------------------------------------------------

	add_shortcode('instant_gallery', 'instant_gallery');
</pre>
<p>It feels good to have a nice quick win after the big block of code from Step 2.4. Here we&#8217;re just defining a very simple shortcode so that we will be able to add the gallery to our WordPress posts or pages.</p>
<p>This takes our function, called &#8216;<code>instant_gallery</code>&#8216; which is defined above, and creates a new shortcode with an identical name. We can then insert the gallery into our posts or pages using the shortcode <code>[instant_gallery]</code>.</p>
<p>There are plenty of in-depth articles about shortcodes out there, including some good ones right here on Wptuts+. If you are new to shortcodes, here are some good starting points:</p>
<ul>
<li><a href="http://wp.tutsplus.com/tutorials/getting-started-with-wordpress-shortcodes/" target="_blank">Getting Started with WordPress Shortcodes</a></li>
<li><a href="http://wp.tutsplus.com/tutorials/theme-development/wordpress-shortcodes-the-right-way/" target="_blank">WordPress Shortcodes: The Right Way</a></li>
<li><a href="http://wp.tutsplus.com/tutorials/plugins/quick-tip-using-shortcodes-in-theme-development/" target="blank">Quick Tip: Using Shortcodes in Theme Development</a></li>
<li><a href="http://codex.wordpress.org/Shortcode_API" target="_blank">WordPress Shortcode API</a></li>
</ul>
<hr />
<h3>Step 2.6: Gather Our Thoughts</h3>
<p>Whew! Ok, so that&#8217;s all the code for the gallery itself. The code we&#8217;ve written so far will retrieve a list of image attachments from the current WordPress post or page and then automatically generate a gallery according to the markup we provided. The shortcode then gives us a convenient way to insert our galleries into our posts or pages.</p>
<p>If we upload some awesome images of seahorses and jellyfish and then check our results, here is what we will have at this point:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-no-js-no-css.png" border="0" /></div>
<p>From a WordPress point of view, we have done what we need to do. Without JavaScript, however, the gallery won&#8217;t actually do anything. Without CSS, it won&#8217;t look very good, either. So, let&#8217;s take a minute to digest what we&#8217;ve done so far, and then we will move on to the next step where we make our gallery come alive!</p>
<hr />
<h2><span>Step 3</span> The JavaScript</h2>
<p>As you might expect, Instant Gallery relies on the magic of jQuery to achieve the basic level of interactivity that it requires. There are actually two parts to this. The first is loading the jQuery library into our theme correctly, and the second is the actual jQuery code which will create the behavior we need (namely, swapping images and image titles when a thumbnail is clicked).</p>
<p>Both of these parts offer a good opportunity to employ some insights and WordPress best practices, so if you are new to working with jQuery in the context of WordPress, pay special attention!</p>
<hr />
<h3>Step 3.1: Using Enqueue Script to Load jQuery in WordPress</h3>
<p>As you may know, jQuery (as well as many other JavaScript libraries) come pre-loaded with WordPress. For the sake of simplicity, we will use the version of jQuery included with WordPress for this example.</p>
<p>This is a good opportunity to use the WordPress <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" target="_blank"><code>wp_enqueue_script</code></a> function. This is the &#8220;right&#8221; way to load scripts in WordPress. It ensures that the scripts are loaded at the proper place and time as WordPress executes, and that conflicts are avoided.</p>
<p>The <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" target="_blank"><code>wp_enqueue_script</code></a> function can be confusing, but fortunately there are plenty of good articles about it out there. Here are some useful resources about <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" target="_blank"><code>wp_enqueue_script</code></a>:</p>
<ul>
<li><a href="http://wp.tutsplus.com/articles/how-to-include-javascript-and-css-in-your-wordpress-themes-and-plugins/" target="_blank">How to Include JavaScript and CSS in Your WordPress Themes and Plugins</a></li>
<li><a href="http://digwp.com/2009/06/use-google-hosted-javascript-libraries-still-the-right-way/" target="_blank">Use Google-Hosted JavaScript Libraries (&#8230;still the Right Way) (Updated Dec. 2011)</a></li>
</ul>
<pre name="code" class="php">
	//-------------------------------------------------
	// Enqueue jQuery
	//-------------------------------------------------

	function wptuts_enqueue_jquery() {

		wp_enqueue_script('jquery');

	}

	// Only add the javascript if we are NOT on the admin screen
	add_action("wp_enqueue_scripts", "wptuts_enqueue_jquery", 11);
</pre>
<p>Notice that we attach this function to the WordPress hook &#8220;<code>wp_enqueue_scripts</code>&#8221; which loads all the scripts that have been enqueued by &#8220;<code>wp_enqueue_script</code>&#8220;.  Subtle difference there, but it is important!</p>
<p>Here is an <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" target="_blank">important note about <code>wp_enqueue_scripts</code> from the WP Codex</a>:</p>
<p><strong><em><code>wp_enqueue_scripts</code> hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.</em></strong></p>
<hr />
<h3>Step 3.2: Using jQuery to Bring Instant Gallery to Life</h3>
<p>Now we can move on to the jQuery code that powers the swapping of images and titles. We only need a few lines of code to accomplish this. Some of you out there who are well versed in jQuery may even be able to suggest some more efficient ways to get the job done!</p>
<p>As we did with the WordPress code in Step 2, let&#8217;s walk through this conceptually before we get into the code itself. When we click on a thumbnail, we want a few things to happen:</p>
<ul>
<li><strong>First and most importantly</strong>, we want to swap out the existing image in the main hero position for another large image &ndash; the one that corresponds to the thumbnail we clicked on.</li>
<li><strong>Second</strong>, we want to replace the title of the old image with the one that corresponds to the new image. We will do this by taking advantage of the WordPress file naming scheme. We will talk about how to do that in just a moment.</li>
<li><strong>Third</strong>, we want to highlight the thumbnail corresponding to our large image at any given time. As we saw in Step 2.4 above, the way we designate this is with a class of &#8216;selected&#8217; on the current thumbnail.</li>
<li><strong>Finally</strong>, when a new image is chosen, we remove the class of &#8216;selected&#8217; from <em>all</em> images, and then add it back again to the newly selected thumbnail.</li>
</ul>
<p>So, with those key actions in mind, let&#8217;s see what this looks like in jQuery:</p>
<pre name="code" class="php">
	//-------------------------------------------------
	// Activate Instant Gallery
	//-------------------------------------------------

	function activate_instant_gallery() {
	?&gt;

		&lt;script&gt;

			// Wrap the jQuery code in the generic function to allow use of
			// the $ shortcut in WordPress's no-conflict jQuery environment

			( function ($) {

				$('#ig-thumbs').delegate('img','click', function(){		// When someone clicks on a thumbnail

					$('#ig-hero').attr('src',$(this).attr('src').replace('-150x150',''));	// Replace the Full Sized version of selected image

					$('#ig-thumbs li img').removeClass("selected");		// Remove "selected" class from all thumbnails
					$(this).addClass("selected");						// Add "selected" class to selected thumbnail

					$('#ig-title').html($(this).attr('alt'));			// Replace the Title with Title selected image
				});

			})(jQuery);

		&lt;/script&gt;

	&lt;?php
	}

	// Hook into footer so gallery becomes active after page loads
	add_action('wp_footer','activate_instant_gallery');	

	?&gt;
</pre>
<p>Fortunately, the jQuery code is relatively simple, and corresponds nicely to our bullet list of required actions above.</p>
<p>The code is pretty well-documented, so if you don&#8217;t understand a line, the comments should help. Even so, let&#8217;s break down the jQuery, line by line (leaving aside the generic &#8220;wrapper function&#8221; of <code>( function ($) { } )</code> which we will discuss in a moment).
<p>The line that begins <code>$('#ig-thumbs').delegate</code> is what defines the scope of our function. It is saying, whenever someone clicks on an image object (<code>img</code>) inside a container with an ID of <code>#ig-thumbs</code>, then execute the actions within the function.</p>
<p>The next line, which begins <code>$('#ig-hero')</code>, handles the actual swapping of our current image for the large image that corresponds to the thumbnail that was clicked. In this jQuery function, the thumbnail that was clicked is referred to as &#8220;this&#8221; because it was the subject of the action &#8220;click&#8221;; it is the thing that was clicked upon and triggered the function.</p>
<p>The method for accomplishing the image swap takes advantage of the WordPress file naming scheme. For example: When you upload an image called <strong>my-image.jpg</strong>, WordPress will create several different sizes of that image. One automatically created size will be a &#8220;Thumbnail&#8221; size which is, by default, a 150&#215;150 square cropped out of your original image. WordPress will name this file <strong>my-image-150&#215;150.jpg</strong>. It simply adds a &#8220;-150&#215;150&#8243; to the end of your filename, right before the file extension.</p>
<p>So, if we want to replace a thumbnail version of an image with the full-sized version of that image, then we just have to remove the &#8220;-150&#215;150&#8243; from the filename. This is what our jQuery is doing to swap the images.</p>
<p>If we wanted to replace the thumbnail with a different size of the image, but not the full sized image, we would need to know the dimensions of that other size, and then we could just switch the dimensions. For example, if we wanted to switch out <strong>my-image-150&#215;150.jpg</strong> for a Medium sized image of 600&#215;300, then we would just use the jQuery code to swap the &#8220;-150&#215;150&#8243; with a &#8220;-600&#215;300&#8243;, and we would be left with <strong>my-image-600&#215;300.jpg</strong>.</p>
<p>Next, with the line that begins <code>$('#ig-thumbs li img')</code>, we just remove the CSS class of &#8220;selected&#8221; from <em>all</em> of the thumbnails, and then the line below that adds the class of &#8220;selected&#8221; to &#8220;this&#8221;; that is, the image that was clicked.</p>
<p>Finally, with the line that begins <code>$('#ig-title')</code>, we switch the Title of the old image with that of the new image. This line takes the contents of a containing element with an ID of <code>#ig-title</code></p>
<h3>Step 3.3: Using jQuery in the Context of WordPress</h3>
<p>Now, since we are performing all of these operations within the context of WordPress, we should be aware of an important detail about how WordPress loads jQuery.</p>
<p>WordPress runs jQuery in &#8220;no conflict mode&#8221; so as to avoid conflicts with other JavaScript libraries. In practical terms this means that the useful <code>$</code> shortcut commonly used in jQuery won&#8217;t work in WordPress by default.</p>
<p>Fortunately, this topic has been discussed at length already. If you are interested in learning more about the reasons for this, <a href="http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/" target="_blank">Chris Coyier has a great article on Digging Into WordPress that addresses precisely this issue</a>. For the purposes of this article, we just need to wrap our jQuery function in a generic function to re-enable use of the <code>$</code> shortcut within our code snippet.</p>
<p>Finally we add this code using a built in WordPress hook &ndash; <a href="http://codex.wordpress.org/Function_Reference/wp_footer" target="_blank">wp_footer</a> &ndash; to load the script correctly and only after the rest of the page has loaded.</p>
<p>With the jQuery in place, let&#8217;s take a look at what we have so far. Now our gallery is interactive, and clicking on one of the thumbnails correctly replaces the main image and corresponding title. In the example image below, you can see that we&#8217;ve clicked on the second thumbnail and both the main image and its title have been replaced as we would expect.</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-no-css.png" border="0" /></div>
<p>So, it works, but it still doesn&#8217;t look very good. Fortunately, we can tidy things up with some basic CSS. And that&#8217;s just what we&#8217;ll do in the next step.</p>
<hr />
<h2><span>Step 4</span> The CSS</h2>
<h3>Step 4.1: CSS for Instant Gallery</h3>
<p>Now it is finally time to style our creation and make it look more like an actual image gallery. Since the major focus of this tutorial was on the WordPress and jQuery functionality, I&#8217;ve kept the CSS for this gallery extremely simple. Here is the CSS code for the gallery:</p>
<pre name="code" class="css">
	/* Instant Gallery */

	#instant-gallery {
		overflow: hidden;
		display: block;
		width: 100%;
		margin-bottom: 1.5em;
	}

	/* Main Display Area */

	#ig-main {
		width: 100%;
	}

	#ig-hero {
	}

	#ig-title {
		margin-top: 1.5em;
		margin-bottom: 1.5em;
		line-height: 1.5em;
	}

	/* Thumbnails */

	#ig-thumbs {
		overflow: hidden;
		margin: 0;
	}

	#ig-thumbs li {
		margin-right: 1.5em;
		margin-bottom: 1.5em;
		float: left;
		display: block;
		cursor: pointer;
	}

	#ig-thumbs img {
		width: 75px;				/* Customize to change Thumbnail Width */
		height: 75px;				/* Customize to change Thumbnail Height */
		padding: 1px;
		border: 1px solid #ddd;
	}

	#ig-thumbs li img:hover,
	#ig-thumbs li img.selected {
		border: 1px solid #aaa !important;
	}
</pre>
<p>There is nothing too complicated about our CSS. Just the basic selectors and styles necessary to create the gallery. If you want to modify the CSS to make your gallery a bit more fancy, I have provided all of the selectors you would need to do so.</p>
<p>One thing to notice here is that I&#8217;ve constrained the size of the thumbnails to 75&#215;75 instead of the 150&#215;150 size at which we retrieved them from WordPress. The 150&#215;150 size is a little too large for my tastes; I like the smaller thumbnails so you can fit more under the gallery. If you want to use a different size, all you have to do is change the width and height of the thumbnail images on the two lines marked on the CSS.</p>
<hr />
<h3>Step 4.2: Using Enqueue Style to Load CSS in WordPress</h3>
<p>Perhaps more interesting than the CSS itself is the manner that we use to load it. We could just do a simple link tag and hook it into our header using the <a href="http://codex.wordpress.org/Plugin_API/Action_Reference/wp_head" target="blank"><code>wp_head</code></a> hook, but there is a better way.</p>
<p>Taking a hint from the <code>enqueue_script</code> function that we used to load jQuery, we can use a similar function, <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_style" target="_blank"><code>wp_enqueue_style</code></a>, to load our style sheet. As with <code>enqueue_script</code>, this is the preferred way to load stylesheets within WordPress. It is good to practice these techniques even with simple projects such as this because it allows you to focus on understanding the technique and why it works without worrying about debugging massive amounts of code. There is a certain satisfaction in doing something simple very well!</p>
<pre name="code" class="php">
	//----------------------------------------------------------------------
	// Import Stylesheet
	//----------------------------------------------------------------------

	function add_stylesheets() {

		// change this path to load your own custom stylesheet
		$css_path = WP_PLUGIN_URL . '/instant-gallery/instant-gallery.css';

		// registers your stylesheet
		wp_register_style( 'instantGalleryStyles', $css_path );

		// loads your stylesheet
		wp_enqueue_style( 'instantGalleryStyles' );
	}

	// Only add the stylesheet if we are NOT on the admin screen
	if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_stylesheets' );
</pre>
<p>So that is how you use <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_style" target="_blank"><code>wp_enqueue_style</code></a>. Very similar to <code>enqueue_script</code>. You&#8217;ll notice that there is another command in here as well: <a href="http://codex.wordpress.org/Function_Reference/wp_register_style"><code>wp_register_style</code></a>. This function simply registers a CSS file with WordPress for later use with <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_style" target="_blank"><code>wp_enqueue_style</code></a>.</p>
<p>Now our image gallery finally looks as good as it functions!</p>
<hr />
<h2>All Together Now</h2>
<p>Check out the finished product:</p>
<div class="tutorial_image"><img src="http://wptutsplus.s3.amazonaws.com/265_How_to_Create_an_Instant_Image_Gallery_Plugin_for_WordPress/instant-gallery-complete.png" border="0" /></div>
<p>It looks very simple, and that&#8217;s exactly what we want. The point of this gallery is to be the simplest, fastest way to automatically generate an image gallery from images uploaded to a WordPress post of page, nothing more!</p>
<p>Please feel free to check out a live demo of <a href="http://www.heyjohnsexton.com/projects/instant-gallery-for-wordpress/" target="_blank">Instant Gallery for WordPress</a> on my personal website.</p>
<p>The completed code is too long to display here in full, so please feel free to download the source files (at the top of the article) and have a look at everything on your own.</p>
<hr />
<h2>Conclusion</h2>
<p>We have just created an instant image gallery with thumbnail navigation for a WordPress!</p>
<p>Throughout this tutorial I&#8217;ve done my best to incorporate good practices on everything from clear markup, semantic CSS, and even the way stylesheets and javascript are loaded. If you played along and worked through the steps, then I hope you learned a new technique or two. If you are just here for the finished code, I hope you find it useful and that you can use it confidently and with the knowledge that you are using some simple code that was made with love.</p>
<p>As with all coding projects, there are always ways to make improvements. If you can think of any way to make this code better or more robust, I welcome any and all constructive feedback in the comments!</p>
<p>I also welcome any and all suggestions on how to improve the plugin and make it more powerful or elegant. I am not very interested, however, in making it more complicated or adding a bunch of features. There are lots of full featured image galleries out there already, and I would like this one to remain simple and fulfil one very specific purpose.</p>
<p>Finally, I would like to thank Japh Thomson for giving me the opportunity to write for Wptuts+, and thank Envato for building a great educational community on the web. Most importantly, thank <strong>you</strong> for reading!</p>
<p>I look forward to your feedback, please let me know in the comments if you use Instant Gallery on any of your websites!</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/plugins/how-to-create-an-instant-image-gallery-plugin-for-wordpress/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Add Post Type Archive Links to Your Menu</title>
		<link>http://wp.tutsplus.com/tutorials/theme-development/add-post-type-archive-links-to-your-menu/</link>
		<comments>http://wp.tutsplus.com/tutorials/theme-development/add-post-type-archive-links-to-your-menu/#comments</comments>
		<pubDate>Mon, 07 May 2012 09:24:28 +0000</pubDate>
		<dc:creator>Stephen Harris</dc:creator>
				<category><![CDATA[Theme Development]]></category>
		<category><![CDATA[custom menus]]></category>
		<category><![CDATA[Custom Post Types]]></category>
		<category><![CDATA[plugin development]]></category>
		<guid isPermaLink="false">http://wp.tutsplus.com/?p=25314</guid>
		<description><![CDATA[<p>A common request, particularly for those who have created custom post types like &#8216;News&#8217; or &#8216;Events&#8217;, is to add a link to their post type&#8217;s archive page on their navigation menu. Currently, however, this can only be done by manually entering the post type archive URL. Apart from being fairly inelegant, this solution has a few drawbacks: it doesn&#8217;t always appear as &#8216;current&#8217;, if you change your permalink structure it could break the link, manually adding the URLs is tedious and the link does not appear as &#8216;current&#8217; when on a post of that post type.</p>
<p>In this tutorial I will show you how to produce a plugin that creates a meta-box on your Appearance -&gt; Menu page which allows you to add post type archive links. These links don&#8217;t suffer from the drawbacks mentioned above.<span id="more-25314"></span></p>
<hr />
<h2><span>Step 1</span> Creating a Plugin</h2>
<p>This plugin will be called &#8216;My Post Type Archive Links&#8217;, and to that end first create a folder called <strong>my-post-type-archive-links</strong> under your <strong>/wp-content/plugins/</strong> folder, and inside that create a file <strong>my-post-type-archive-links.php</strong>. This file is the main plugin file. We&#8217;re going to wrap it in a class &ndash; this is simply so we don&#8217;t have to worry about our function names clashing with WordPress or other plugins: we simply need to make sure that our class name is unique. Add the following to <strong>my-post-type-archive-links.php</strong></p>
<pre name="code" class="php">
&lt;?php
/*
Plugin Name: My Post Type Archive Links
Version: 1.0
Description: Adds a metabox to the Appearance -&gt; Menu page to add post type archive links
Author: Stephen Harris
Author URI: http://profiles.wordpress.org/users/stephenh1988/
*/

class My_Post_Type_Archive_Link {
	//Everything will go here
}
My_Post_Type_Archive_Link::load();
?&gt;
</pre>
<p>Everything in this tutorial will sit inside that class.</p>
<hr />
<h2><span>Step 2</span> Loading the Plugin</h2>
<p>When the plugin file is loaded, it will fire the class method <code>load()</code>. This method will be responsible for adding actions and filters onto various WordPress hooks. We&#8217;ll go through each of them in the subsequent steps, but it also provides a useful summary. Add the following method to our class:</p>
<pre name="code" class="php">
	public function load(){
		// Hook function to add the metabox to the Menu page
		add_action( 'admin_init', array(__CLASS__,'add_meta_box'));

		// Javascript for the meta box
		add_action( 'admin_enqueue_scripts', array(__CLASS__,'metabox_script') );

		// Ajax callback to create menu item and add it to menu
		add_action('wp_ajax_my-add-post-type-archive-links', array( __CLASS__, 'ajax_add_post_type'));

		// Assign menu item the appropriate url
		add_filter( 'wp_setup_nav_menu_item',  array(__CLASS__,'setup_archive_item') );

		// Make post type archive link 'current'
		add_filter( 'wp_nav_menu_objects', array(__CLASS__,'maybe_make_current'));
	}
</pre>
<p>Let&#8217;s summarise what each of these parts are doing:</p>
<ol>
<li><strong>Add a meta-box</strong> &ndash; Fairly self explanatory. The hooked function will be responsible for adding our meta box.</li>
<li><strong>Enqueue JavaScript</strong> &ndash; We use the <code>admin_enqueue_scripts</code> hook to enqueue our JavaScript file. Our JavaScript, when &#8216;add to menu&#8217; is clicked, will trigger an AJAX request.</li>
<li><strong>AJAX callback</strong> &ndash; This function is responsible for handling the above AJAX request. It will create the menu items and add them onto the menu.</li>
<li><strong>Menu item set up</strong> &ndash; This ensures that when the archive link appears on your menu it correctly points to the post type&#8217;s archive.</li>
<li><strong>Maybe make current</strong> &ndash; Whenever a menu appears its items are passed through a filter, we will ensure that the class &#8216;<code>current-menu-item</code>&#8216; is added to the appropriate post type link.</li>
</ol>
<hr />
<h2><span>Step 3</span> Adding the Metabox</h2>
<p>First we define our <code>add_meta_box</code> method, which simply calls the WordPress function <code>add_meta_box()</code>. The details of this function have been covered many times before, but if you are unsure you can read up on it in <a href="http://codex.wordpress.org/Function_Reference/add_meta_box">the Codex pages</a>.</p>
<pre name="code" class="php">
	public function add_meta_box() {
		add_meta_box( 'post-type-archives', __('Post Types','my-post-type-archive-links'),array(__CLASS__,'metabox'),'nav-menus' ,'side','low');
	}
</pre>
<p>Next we define the meta-box callback function which is responsible for displaying the metabox&#8217;s insides:</p>
<pre name="code" class="php">
	public function metabox( ) {
		global $nav_menu_selected_id;

		//Get post types
		$post_types = get_post_types(array('public'=&gt;true,'_builtin'=&gt;false), 'object');?&gt;

		&lt;!-- Post type checkbox list --&gt;
		&lt;ul id="post-type-archive-checklist"&gt;
		&lt;?php foreach ($post_types as $type):?&gt;
			&lt;li&gt;&lt;label&gt;&lt;input type="checkbox" value ="&lt;?php echo esc_attr($type-&gt;name); ?&gt;" /&gt; &lt;?php echo esc_attr($type-&gt;labels-&gt;name); ?&gt; &lt;/label&gt;&lt;/li&gt;
		&lt;?php endforeach;?&gt;
		&lt;/ul&gt;&lt;!-- /#post-type-archive-checklist --&gt;

		&lt;!-- 'Add to Menu' button --&gt;
		&lt;p class="button-controls" &gt;
			&lt;span class="add-to-menu" &gt;
				&lt;input type="submit" id="submit-post-type-archives" &lt;?php disabled( $nav_menu_selected_id, 0 ); ?&gt; value="&lt;?php esc_attr_e('Add to Menu'); ?&gt;" name="add-post-type-menu-item"  class="button-secondary submit-add-to-menu" /&gt;
			&lt;/span&gt;
		&lt;/p&gt;
	&lt;?php
	}
</pre>
<p>This method simply gets all public custom post types with <a href="http://codex.wordpress.org/Function_Reference/get_post_types"><code>get_post_types()</code></a> and then loops through them to create a list of checkboxes. Each checkbox has the name of the post type as its value. In the next step we add some javascript that will be triggered when a user clicks the &#8216;Add to Menu&#8217; button.</p>
<hr />
<h2><span>Step 4</span> The JavaScript</h2>
<p>We only want to enqueue our JavaScript on the Appearance -&gt; Menu admin page. We&#8217;ve used the <a href="http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts"><code>admin_enqueue_scripts</code></a> hook which fires only on admin pages and passes the page&#8217;s hook as an argument. The hook for the Appearance -&gt; Menu page is <strong>nav-menus.php</strong>. After enqueueing our script we use <a href="http://codex.wordpress.org/Function_Reference/wp_localize_script"><code>wp_localize_script</code></a> to make the nonce available in our JavaScript. We include it in the AJAX request to help verify that the action was intended.</p>
<pre name="code" class="php">
	public function metabox_script($hook) {
		if( 'nav-menus.php' != $hook )
			return;

		//On Appearance>Menu page, enqueue script:
		wp_enqueue_script( 'my-post-type-archive-links_metabox', plugins_url('/metabox.js', __FILE__), array('jquery'));

		//Add nonce variable
		wp_localize_script('my-post-type-archive-links_metabox','MyPostTypeArchiveLinks', array('nonce'=&gt;wp_create_nonce('my-add-post-type-archive-links')));
	}
</pre>
<p>In the previous step the &#8216;Add to Menu&#8217; button was given the ID <code>submit-post-type-archives</code>. We now use jQuery to target that button and, when clicked, send an AJAX request to create the menu item and append it to the menu. The following is the only part of this tutorial that lives outside our class. It should go in a file called <strong>metabox.js</strong>, inside our plug-in folder.</p>
<pre name="code" class="js">
	jQuery(document).ready(function($) {
		$('#submit-post-type-archives').click(function(event) {
			event.preventDefault();

			/* Get checked boxes */
			var postTypes = [];
			$('#post-type-archive-checklist li :checked').each(function() {
				postTypes.push($(this).val());
			});

			/* Send checked post types with our action, and nonce */
			$.post( ajaxurl, {
					action: "my-add-post-type-archive-links",
					posttypearchive_nonce: MyPostTypeArchiveLinks.nonce,
					post_types: postTypes
				},

				/* AJAX returns html to add to the menu */
				function( response ) {
					$('#menu-to-edit').append(response);
				}
			);
		})
	});
</pre>
<p>Notice the URL we are sending the request to: <code>ajaxurl</code>. We haven&#8217;t defined it anywhere. It&#8217;s a global variable set by WordPress <em>on the admin side only</em> which points to the page that WordPress uses to handle AJAX requests. When the submit button is clicked, the names of the checked post types, a unique action and nonce are all sent to this URL. When WordPress receives the request it triggers the <code>wp_ajax_my-add-post-type-archive-links</code> hook. The nonce is a security precaution to help verify that the action was intended.</p>
<hr />
<h2><span>Step 5</span> The AJAX Callback</h2>
<p>We now define the AJAX callback function <code>ajax_add_post_type</code>.</p>
<pre name="code" class="php">
	public function ajax_add_post_type() {

		if ( ! current_user_can( 'edit_theme_options' ) )
			die('-1');

		check_ajax_referer('my-add-post-type-archive-links', 'posttypearchive_nonce');

		require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

		if(empty($_POST['post_types']))
			exit;

		// Create menu items and store IDs in array
		$item_ids=array();
		foreach ( (array) $_POST['post_types'] as $post_type) {
			$post_type_obj = get_post_type_object($post_type);

			if(!$post_type_obj)
				continue;

			$menu_item_data= array(
				'menu-item-title' =&gt; esc_attr($post_type_obj-&gt;labels-&gt;name),
				'menu-item-type' =&gt; 'post_type_archive',
				'menu-item-object' =&gt; esc_attr($post_type),
				'menu-item-url' =&gt; get_post_type_archive_link($post_type)
			);

			//Collect the items' IDs.
			$item_ids[] = wp_update_nav_menu_item(0, 0, $menu_item_data );
		}

		// If there was an error die here
		if ( is_wp_error( $item_ids ) )
			die('-1');

		// Set up menu items
		foreach ( (array) $item_ids as $menu_item_id ) {
			$menu_obj = get_post( $menu_item_id );
			if ( ! empty( $menu_obj-&gt;ID ) ) {
				$menu_obj = wp_setup_nav_menu_item( $menu_obj );
				$menu_obj-&gt;label = $menu_obj-&gt;title; // don't show "(pending)" in ajax-added items
				$menu_items[] = $menu_obj;
			}
		}

		// This gets the HTML to returns it to the menu
		if ( ! empty( $menu_items ) ) {
			$args = array(
				'after' =&gt; '',
				'before' =&gt; '',
				'link_after' =&gt; '',
				'link_before' =&gt; '',
				'walker' =&gt; new Walker_Nav_Menu_Edit
			);
			echo walk_nav_menu_tree( $menu_items, 0, (object) $args );
		}

		// Finally don't forget to exit
		exit;
	}
</pre>
<p>Let&#8217;s go through this callback a bit at a time. First we check the user&#8217;s permissions, verify the nonce and load the <strong>nav-menu.php</strong> page (we need some of the functions).</p>
<pre name="code" class="php">
		if ( ! current_user_can( 'edit_theme_options' ) )
			die('-1');

		check_ajax_referer('my-add-post-type-archive-links','posttypearchive_nonce');

		require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

		if(empty($_POST['post_types']))
			exit;
</pre>
<p>We then create a menu item for each selected post type. We first check the post type we received exists by checking the value returned by <a href="http://codex.wordpress.org/Function_Reference/get_post_type_object"><code>get_post_type_object()</code></a>. We can obtain the archive link with the function <a href="http://codex.wordpress.org/Function_Reference/get_post_type_archive_link"><code>get_post_type_archive_link()</code></a></p>
<p>Menu items are in fact posts of post type &#8216;<code>nav_menu_item</code>&#8216; with built-in post meta, including fields relating to &#8216;<code>url</code>&#8216;, &#8216;<code>type</code>&#8216; and &#8216;<code>object</code>&#8216;. The item&#8217;s &#8216;<code>type</code>&#8216; is normally &#8216;<code>custom</code>&#8216;, &#8216;<code>post_type</code>&#8216; or &#8216;<code>taxonomy</code>&#8216; &ndash; but we shall set its value to &#8216;<code>post_type_archive</code>&#8216;. The item&#8217;s &#8216;<code>object</code>&#8216; meta value is normally only used for items of &#8216;<code>post_type</code>&#8216; or &#8216;<code>taxonomy</code>&#8216; type and refers to post type or taxonomy the link refers to. We&#8217;ll use this to store the post type of the archive link.</p>
<pre name="code" class="php">
		// Create menu items and store IDs in array
		$item_ids=array();
		foreach ( (array) $_POST['post_types'] as $post_type) {
			$post_type_obj = get_post_type_object($post_type);

			if(!$post_type_obj)
				continue;

			$menu_item_data= array(
				'menu-item-title' =&gt; esc_attr($post_type_obj-&gt;labels-&gt;name),
				'menu-item-type' =&gt; 'post_type_archive',
				'menu-item-object' =&gt; esc_attr($post_type),
				'menu-item-url' =&gt; get_post_type_archive_link($post_type)
			);

			// Collect the items' IDs.
			$item_ids[] = wp_update_nav_menu_item(0, 0, $menu_item_data );
		}

		// If there was an error die here
		if ( is_wp_error( $item_ids ) )
			die('-1');
</pre>
<p>Next we simply generate the HTML which will be added to the menu. We use the <code>$item_ids</code> array to get an array of menu items and pass this to a WordPress walker class to do the hard work for us.</p>
<pre name="code" class="php">
		//Set up menu items
		foreach ( (array) $item_ids as $menu_item_id ) {
			$menu_obj = get_post( $menu_item_id );
			if ( ! empty( $menu_obj-&gt;ID ) ) {
				$menu_obj = wp_setup_nav_menu_item( $menu_obj );
				$menu_obj-&gt;label = $menu_obj-&gt;title; // don't show "(pending)" in ajax-added items
				$menu_items[] = $menu_obj;
			}
		}

		//This gets the HTML to returns it to the menu
		if ( ! empty( $menu_items ) ) {
			$args = array(
				'after' =&gt; '',
				'before' =&gt; '',
				'link_after' =&gt; '',
				'link_before' =&gt; '',
				'walker' =&gt; new Walker_Nav_Menu_Edit
			);
			echo walk_nav_menu_tree( $menu_items, 0, (object) $args );
		}

		//Finally don't forget to exit
		exit;
</pre>
<hr />
<h2><span>Step 6</span> The Menu Item</h2>
<p>Unfortunately, because of a bug with WordPress, if your item&#8217;s type is not &#8216;<code>taxonomy</code>&#8216;, &#8216;<code>custom</code>&#8216; or &#8216;<code>post_type</code>&#8216; the URL gets removed. To counter this, when a &#8216;<code>post_type_archive</code>&#8216; link is used in a menu, we manually re-add the URL. This also ensures the archive link is &#8216;up to date&#8217; (in case your permalink structure has been changed).</p>
<pre name="code" class="php">
	public function setup_archive_item($menu_item){
		if($menu_item-&gt;type !='post_type_archive')
		 	return $menu_item;

		$post_type = $menu_item-&gt;object;
		$menu_item-&gt;url =get_post_type_archive_link($post_type);

		return $menu_item;
	}
</pre>
<hr />
<h2><span>Step 7</span> Making the Link Current</h2>
<p>Finally we need to make the item &#8216;current&#8217; when we are on the appropriate page. I want the post type archive link to be highlighted as current if we are on that archive page, or viewing a single post of that type. To do this I check:</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/is_post_type_archive"><code>is_post_type_archive()</code></a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/is_singular"><code>is_singular()</code></a></li>
</ul>
<p>To make the item current, we simply need to add <code>current-menu-item</code> to the item&#8217;s classes which are stored in <code>$item-&gt;classes</code>. We then have to loop through its parents in the menu and add the classes <code>current_item_parent</code> and <code>current_item_ancestor</code>. Let&#8217;s look at each bit individually:</p>
<p>We loop through each of the items in the menu:</p>
<pre name="code" class="php">
	public function maybe_make_current($items) {
		foreach ($items as $item) {
			// This is where we check the item
		}
		return $items;
	}
</pre>
<p>If the item is not of &#8216;<code>post_type_archive</code>&#8216; or if it is, but we don&#8217;t want it to make it &#8216;current&#8217;, we simply skip on to the next item. Recall that for our archive links, the post type is stored as the item&#8217;s object. So inside the <code>foreach</code> loop:</p>
<pre name="code" class="php">
			if('post_type_archive' != $item-&gt;type)
				continue;

			$post_type = $item-&gt;object;
			if(!is_post_type_archive($post_type)&#038;&#038; !is_singular($post_type))
				continue;
</pre>
<p>If we do want to make it current we give it the appropriate class and then grab its parents in the menu. A menu item&#8217;s parent are stored as post meta with meta key <code>_menu_item_menu_item_parent</code>.</p>
<pre name="code" class="php">
		//Make item current
		$item-&gt;current = true;
		$item-&gt;classes[] = 'current-menu-item';

		//Get menu item's ancestors:
		$_anc_id = (int) $item-&gt;db_id;
		$active_ancestor_item_ids=array();

		while(( $_anc_id = get_post_meta( $_anc_id, '_menu_item_menu_item_parent', true ) ) &amp;&amp; ! in_array( $_anc_id, $active_ancestor_item_ids )  ) {
			$active_ancestor_item_ids[] = $_anc_id;
		}
</pre>
<p>We then loop through the menu items and give the &#8216;current&#8217; item&#8217;s parents and ancestors the appropriate classes.</p>
<pre name="code" class="php">
		// Loop through the items and give ancestors and parents the appropriate class
		foreach ($items as $key=&gt;$parent_item) {
			$classes = (array) $parent_item-&gt;classes;

			// If menu item is the parent
			if ($parent_item-&gt;db_id == $item-&gt;menu_item_parent ) {
				$classes[] = 'current-menu-parent';
				$items[$key]-&gt;current_item_parent = true;
			}

			// If menu item is an ancestor
			if ( in_array(  intval( $parent_item-&gt;db_id ), $active_ancestor_item_ids ) ) {
				$classes[] = 'current-menu-ancestor';
				$items[$key]-&gt;current_item_ancestor = true;
			}

			$items[$key]-&gt;classes = array_unique( $classes );
		}
</pre>
<p>Putting that function together:</p>
<pre name="code" class="php">
	public function maybe_make_current($items) {
		foreach ($items as $item) {
			if('post_type_archive' != $item-&gt;type)
				continue;

			$post_type = $item-&gt;object;
			if(!is_post_type_archive($post_type)&#038;&#038; !is_singular($post_type))
				continue;

			// Make item current
			$item-&gt;current = true;
			$item-&gt;classes[] = 'current-menu-item';

			// Get menu item's ancestors:
			$_anc_id = (int) $item-&gt;db_id;
			$active_ancestor_item_ids=array();

			while(( $_anc_id = get_post_meta( $_anc_id, '_menu_item_menu_item_parent', true ) ) &amp;&amp; ! in_array( $_anc_id, $active_ancestor_item_ids )  ) {
				$active_ancestor_item_ids[] = $_anc_id;
			}

			// Loop through ancestors and give them 'ancestor' or 'parent' class
			foreach ($items as $key=&gt;$parent_item) {
				$classes = (array) $parent_item-&gt;classes;

				// If menu item is the parent
				if ($parent_item-&gt;db_id == $item-&gt;menu_item_parent ) {
					$classes[] = 'current-menu-parent';
					$items[$key]-&gt;current_item_parent = true;
				}

				// If menu item is an ancestor
				if ( in_array(  intval( $parent_item-&gt;db_id ), $active_ancestor_item_ids ) ) {
					$classes[] = 'current-menu-ancestor';
					$items[$key]-&gt;current_item_ancestor = true;
				}

				$items[$key]-&gt;classes = array_unique( $classes );
			}

		}
		return $items;
	}
</pre>
<p>All that remains is to go to your plugins admin page and activate the plugin.</p>
<hr />
<h2>Conclusion</h2>
<p>There is always room for improvement. For instance, with a bit of jQuery you could add a &#8216;Select All&#8217; link underneath the checkboxes or display a &#8216;loading&#8217; symbol while the AJAX is processing. Now this plugin isn&#8217;t the simplest solution &ndash; but it does work well and avoids the pitfalls of simply adding a custom link. The above plugin in it&#8217;s entirety can be found <a href="https://github.com/stephenh1988/WordPress-Post-Type-Archive-Links">on my GitHub</a>. If you have any comments or suggestions, feel free to leave a comment or contact me via <a href="https://twitter.com/#!/stephenharris88">Twitter</a>.</p>
]]></description>
		<wfw:commentRss>http://wp.tutsplus.com/tutorials/theme-development/add-post-type-archive-links-to-your-menu/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 0.778 seconds -->

