Add Tags and Categories to WordPress Pages

Some projects call for unconventional practices. Adding categories or tags to WordPress pages is probably one of the practices.

<pre>// Add Page tags and categories to WordPress Pages
function add_category_box_on_page(){
    //add meta box
    add_meta_box('categorydiv', __('Categories'), 'post_categories_meta_box', 'page', 'side', 'low');
    add_meta_box('tagsdiv-post_tag', __('Page Tags'), 'post_tags_meta_box', 'page', 'side', 'low');
    add_action('save_post', 'pp_page_cats_tags_save_postdata');
}
 
add_action('admin_menu', 'add_category_box_on_page');
 
function pp_page_cats_tags_save_postdata( $post_id ) {
 
    $pp_post_type = $_POST['post_type'];
 
    // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
    // to do anything
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
 
    }else{
        // Check permissions
        if ( 'page' == $pp_post_type ) {
            if ( current_user_can( 'edit_page', $post_id ) ){
 
                $pp_post_cats = array();
 
                foreach($_REQUEST['post_category'] as $key=>$val){
                    $pp_post_cats[] = $val;
                }
                wp_set_post_categories( $post_id, $pp_post_cats );
            }
        }
    }
}</pre>

Add this code as well and you will ensure that pages are also displayed in WordPress archives and post lists:

<pre>// This filter ensures that the custom added Page tags and categories are displayed in WordPress archives
add_filter( 'pre_get_posts' , 'ucc_include_custom_post_types' );
function ucc_include_custom_post_types( $query ) {
	global $wp_query;
	 
	/* Don't break admin or preview pages. */
	if ( !is_preview() && !is_admin() && !is_page() && !is_single() && !is_home() ) {
		$args = array(
		'public' => true ,
		'_builtin' => false
		);
		$output = 'names';
		$operator = 'and';
		 
		$post_types = get_post_types( $args , $output , $operator );
		$post_types = array_merge( $post_types , array( 'post', 'page' ) );
	 
		if ($query->is_feed) {
			// Do feed processing here.
		} else {
			$my_post_type = get_query_var( 'post_type' );
			if ( empty( $my_post_type ) )
			$query->set( 'post_type' , $post_types );
		}
	}
	 
	return $query;
}</pre>

Line 5 is kind of important. Here you can use Conditional Tags to prevent pages from being added under those conditions. For instance, we’ve added !is_home() because although we may want pages in our archive pages, we didn’t want them in our main blog index. Have fun.

This code was taken from The WP Ninjas.

Revisions

There are no revisions for this post.

Tags: , ,

No comments yet.

Leave a Reply