Tag Archives: custom post type

New WordPress plugin: Boone’s Sortable Columns

Boone’s Sortable Columns is a new WordPress plugin to make it easier for developers of WordPress plugins and themes to create sortable data tables and lists. Like my recent Boone’s Pagination, this is not a plugin for end users but for developers. (And, by the way, Boone’s Sortable Columns goes with Boone’s Pagination like strawberries go with rhubarb. More on that in a minute.)

If you’re building a client site, you can activate the plugin directly in the WordPress Dashboard, and instantiate the class anywhere in your installation. Or, if you’re the developer of a theme or plugin that you’ll be distributing for wide use, you can simply copy the file boones-sortable-columns.php into your own plugin/theme (I recommend a directory called ‘lib’), and then require it manually when you want to do some sortin’.

The plugin is extensively documented inline. I highly recommend that you crack open the source if you have questions about the kinds of options that Boone’s Sortable Columns provides. But, as a quick introduction, here’s a simple example of how you might use the class in your own plugin. Let’s say you have a custom post type called ‘restaurant’, and you want to display a list of restaurants that is sortable by restaurant name, the date when the restaurant was added to the site, and the name of the person who submitted the restaurant (the post author). Here’s the code you might use for a simple table, with my comments and explanations inline.

<br />
// Include Boone's Sortable Columns. You only need to do this if you're not running it as a<br />
// standalone plugin. Obviously, you'll need to put the proper path for your plugin.<br />
require_once( WP_CONTENT_DIR . '/my-plugin-name/lib/boones-sortable-columns.php' );</p>
<p>// Define an array of column data.<br />
// For more details on these (and more!) arguments, see the plugin's inline docs.<br />
$cols = array(<br />
	array(<br />
		'name'		=> 'title',<br />
		'title'		=> 'Restaurant Name',<br />
		'css_class'	=> 'restaurant-name',<br />
		'is_default'	=> true<br />
	),<br />
	array(<br />
		'name'		=> 'author',<br />
		'title'		=> 'Creator',<br />
		'css_class'	=> 'creator'<br />
	),<br />
	array(<br />
		'name'		=> 'date',<br />
		'title'		=> 'Date Added',<br />
		'css_class'	=> 'date-added',<br />
		'default_order'	=> 'desc'<br />
	)<br />
);</p>
<p>// Create the sorting object based on this column data.<br />
$sortable = new BBG_CPT_Sort( $cols );</p>
<p>// Use some of the data from the $sortable object to help you build a posts query.<br />
// In this example, I've intentionally chosen sortable options that can be passed directly to the<br />
// 'orderby' param, because they are accepted directly by WP_Query (see http://codex.wordpress.org/Function_Reference/WP_Query#Order_.26_Orderby_Parameters for more details).<br />
// In real life, your query might require something more complex, like the building of a meta_query.<br />
$query_args = array(<br />
	'post_type'	=> 'restaurant',<br />
	'orderby'	=> $sortable->get_orderby,<br />
	'order'		=> $sortable->get_order<br />
);</p>
<p>// Fire the query<br />
$restaurants = new WP_Query( $query_args );</p>
<p>// Now let's create the table markup. Here's where the magic really happens.<br />
?></p>
<p>have_posts() ) : ?></p>
<table>
<thead>
<tr>
<p>have_columns() ) : ?><br />
			have_columns ) : $sortable->the_column() ?></p>
<th class="the_column_css_class() ?>"><br />
					<a href="the_column_next_link( 'url' ) ?>">the_column_title() ?></a>
				</th>
<tr>
		</thead>
<tbody>
<p>have_posts() ) : $restaurants->the_post() ?></p>
<tr>
<td class="restaurant-name"></td>
<td class="creator"></td>
<td class="date-added"></td>
</tr>
</tbody>
</table>
<p>

Boone’s Sortable Columns handles everything else for you. It figures out what the current orderby/order parameters are. It figures out what the href on the column headers should be. It even creates CSS selectors for the <th> element that match what WP itself uses in the ‘widefat’ tables on the Dashboard, so that you can take advantage of all the pretty JS and CSS built into the WP admin interface. In fact, if this were a Dashboard page, you could simplify the <thead> described above as follows:

</p>
<thead>
<tr>
have_columns() ) : ?><br />
	have_columns ) : $sortable->the_column() ?><br />
		the_column_th() ?></p>
</tr>
</thead>
<p>

The method the_column_th() will build the markup for you. Ain’t that the bee’s knees?

Together with Boone’s Pagination

Boone’s Sortable Columns is made more scrumptious when combined with Boone’s Pagination. Here’s a compressed (uncommented) version of the example above, this time with some pagination code.

<br />
require_once( WP_CONTENT_DIR . '/my-plugin-name/lib/boones-sortable-columns.php' );<br />
require_once( WP_CONTENT_DIR . '/my-plugin-name/lib/boones-pagination.php' );</p>
<p>$cols = array(<br />
	array(<br />
		'name'		=> 'title',<br />
		'title'		=> 'Restaurant Name',<br />
		'css_class'	=> 'restaurant-name',<br />
		'is_default'	=> true<br />
	),<br />
	array(<br />
		'name'		=> 'author',<br />
		'title'		=> 'Creator',<br />
		'css_class'	=> 'creator'<br />
	),<br />
	array(<br />
		'name'		=> 'date',<br />
		'title'		=> 'Date Added',<br />
		'css_class'	=> 'date-added',<br />
		'default_order'	=> 'desc'<br />
	)<br />
);</p>
<p>$sortable = new BBG_CPT_Sort( $cols );</p>
<p>$pagination = new BBG_CPT_Pagination();</p>
<p>$query_args = array(<br />
	'post_type'	=> 'restaurant',<br />
	'orderby'	=> $sortable->get_orderby,<br />
	'order'		=> $sortable->get_order,<br />
	'paged'		=> $pagination->get_paged,<br />
	'per_page'	=> $pagination->get_per_page<br />
);</p>
<p>$restaurants = new WP_Query( $query_args );</p>
<p>$pagination->setup_query( $restaurants );<br />
?></p>
<p>have_posts() ) : ?></p>
<div class="pagination">
<div class="currently-viewing">
			currently_viewing_text() ?>
		</div>
<div class="pag-links">
			paginate_links() ?>
		</div>
</p></div>
<table>
<thead>
<tr>
		have_columns() ) : ?><br />
			have_columns ) : $sortable->the_column() ?></p>
<th class="the_column_css_class() ?>"><br />
					<a href="the_column_next_link( 'url' ) ?>">the_column_title() ?></a>
				</th>
<tr>
		</thead>
<tbody>
		have_posts() ) : $restaurants->the_post() ?></p>
<tr>
<td class="restaurant-name"></td>
<td class="creator"></td>
<td class="date-added"></td>
</tr>
</tbody>
</table>
<div class="pagination">
<div class="currently-viewing">
			currently_viewing_text() ?>
		</div>
<div class="pag-links">
			paginate_links() ?>
		</div>
</p></div>
<p>

Sweet, huh? If you want to see some real-life, more complex examples of Boone’s Pagination and Boone’s Sortable Columns in use, check out Invite Anyone (where the data is a custom post type, as in the example above – see method invite_anyone_settings_mi_content()) or Unconfirmed (where the data actually comes from a custom query of the wp_signups table – look for the admin_panel_main() method).

You can get Boone’s Sortable Columns from the wordpress.org repo or follow its development on Github.

Hiding WordPress custom post type menu items without disabling edit access

WordPress 3.0’s custom post types are really cool, opening up a whole new world of use cases for WordPress. We used custom post types extensively when developing Anthologize. But there are still some rough spots.

For instance, the ‘show_ui’ parameter of register_post_type() is a little bit too coarse-grained for our purposes. For Anthologize, we wanted to allow the user to edit custom post types with the standard Edit page, but we didn’t want users to be able to access most of these post types through the menu items automatically created by register_post_types (all links to the edit pages would appear on our custom Dashboard panel, in order to reduce redundancy and confusion). With ‘show_ui’ set to true, users could access the edit screens, but they could also access the unwanted menu items; with ‘show_ui’ set to false, the menu items were hidden, but navigating to the Edit pages (directly, via URL) threw a “You don’t have permission to access this page” error.

Here’s how we resolved the dilemma. Note that it’s a bit hackish at the moment. In the future, I hope the WordPress team will split ‘show_ui’ gets into multiple, separate arguments.

  1. In your register_post_type() call, set ‘show_ui’ to true. Here’s an example from Anthologize:
    <br />
    	register_post_type( 'library_items', array(<br />
    		'label' => __('Library Items', 'anthologize' ),<br />
    		'public' => true,<br />
    		'_builtin' => false,<br />
    		'show_ui' => true,<br />
    		'capability_type' => 'page',<br />
    		'hierarchical' => true,<br />
    		'supports' => array('title', 'editor', 'revisions'),<br />
    		'rewrite' => array("slug" => "library_item")<br />
    	));<br />
    	
  2. To remove the unwanted menu items, we’ll take advantage of the fact that WordPress has built-in support for custom menu order. First, we have to tell WordPress to expect a custom menu order. (The following two functions are modified from Anthologize, where they’re methods on a loader class.)
    <br />
    	function toggle_custom_menu_order(){<br />
    		return true;<br />
    	}<br />
    	add_filter( 'custom_menu_order', 'toggle_custom_menu_order' );<br />
    	
  3. Once custom_menu_order has been set to true (step 2), WordPress makes a new filter hook available, menu_order. As the name says, it’s really meant to reorder menu items, but we’ll use it to erase menu items altogether.
    <br />
    	function remove_those_menu_items( $menu_order ){<br />
    		global $menu;</p>
    <p>foreach ( $menu as $mkey => $m ) {<br />
    			$key = array_search( 'edit.php?post_type=library_items', $m );</p>
    <p>if ( $key )<br />
    				unset( $menu[$mkey] );<br />
    		}</p>
    <p>return $menu_order;<br />
    	}<br />
    	add_filter( 'menu_order', 'remove_those_menu_items' ) );<br />
    	

    Here’s what’s happening. The filter hook is meant to modify $menu_order. That’s why remove_those_menu_item() takes $menu_order as an argument, and returns it back to WordPress untouched on the last line of the function. On the first line of the function, we’re taking advantage of the fact that the $menu variable – where menu items are stored for construction into markup later on – is in the global scope. Once we’ve declared that we’ll be using $menu on the first line, we loop through each of the menu items, and when we find one that matches our custom post type (ie, when we find one that contains the string ‘edit.php?post_type=library_items’ – you’ll have to replace the post_type with your own, obviously), it gets removed from the $menu global.

You can iterate this for as many different custom post types as you’d like – just add more potential keys to the foreach loop in remove_those_menu_items(), eg

<br />
	$key = array_search( 'edit.php?post_type=library_items', $m );<br />
	$keyb = array_search( 'edit.php?post_type=some_other_post_type', $m );</p>
<p>if ( $key || $keyb )<br />
		unset( $menu[$mkey] );<br />