Using categories and tags on WordPress pages (not posts)

This may belabouring the obvious to those with more experience, but I busted my chops on this for a couple of weeks, so I thought that I’d share it.

By default, WordPress allows us to use categories and tags on posts only.

The key point here is to remember that both categories and tags are taxonomies.

To allow pages to use categories and tags, include this simple function in your functions.php file.


function addCatAndTagsOnPage(){
    register_taxonomy_for_object_type('post_tag', 'page');
    register_taxonomy_for_object_type('category', 'page');
}
add_action('admin_menu', 'addCatAndTagsOnPage');

Once this is done, you’ll surely want to access your pages that have a given category. In this case, I set it my category.php template.

// Get the current category slug
$cat = get_category( get_query_var( 'cat' ) );

// Arguments for our query to retrieve category taxonomy
$args=array(
   'post_type' => 'page',
   'taxonomy' => 'category',
   'term' => $cat->slug,
);

// Instantiate a value for the query
$the_query = null;

// Perform the query
$the_query = new WP_Query($args);

// Loop over the query results. In this case we're stuffing the title and link in a list
if( $the_query->have_posts() ) {
   echo '<ul>';
   while ($the_query->have_posts()) : $the_query->the_post();
      echo '<li><a href="' . get_permalink() . '" rel="bookmark" title="Permanent Link to ' . get_the_title() . '">' . get_the_title() . '</a></li>';
   endwhile;
   echo '</ul>';
}
wp_reset_query(); // Restore global post data

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *

3,866 Spam Comments Blocked so far by Spam Free Wordpress