Creating Unique Sidebar Content for WordPress Pages using Custom Post Types

In this article, I show how to use WordPress’ custom post functionality to create unique sidebar content blocks for static pages which run off the same template.

A non-profit organization I volunteer for recently requested a way to add contextual content to specific WordPress page sidebars. The content could include quotes, donation and course banners and other images which were related to the content of the page.

The website has almost 100 static pages which use page.php as their template. The challenge was to find functionality which could provide page-specific sidebar content that could easily be administrated by volunteers who had a wide variety of technical backgrounds.

I usually try to provide custom functionality for my clients without resorting to WordPress plugins. Don’t get me wrong, I love plugins for a lot of things such as displaying the latest tweets, optimizing SEO and displaying content via light boxes (all of which are used on this site). I just don’t always care for the excessive quantity of poorly outputted code which often accompanies the functionality.

Overview of Steps Involved

  1. Register a Sidebar custom post type
  2. Create a template include file for the sidebar content block
  3. Include the new sidebar template file in sidebar.php
  4. Create a sidebar entry
  5. Add the sidebar entry to the WordPress static page

1. Register a Sidebar Custom Post Type

In functions.php we would use the register_post_type WordPress function to create the sidebar content post type.

<?php

add_action( 'init', 'create_post_type' );

function create_post_type() {

$labels = array(
    	'name' => __('Sidebar Content'),
    	'singular_name' => __('Sidebar Entry'),
    	'add_new' => __('Add New'),
    	'add_new_item' => __('Add New Sidebar Entry'),
    	'edit_item' => __('Edit Sidebar Entry'),
    	'new_item' => __('New Sidebar Entry'),
    	'view_item' => __('View Sidebar Entry'),
    	'search_items' => __('Search Sidebar Entry'),
    	'not_found' =>  __('No Sidebar Entry found'),
    	'not_found_in_trash' => __('No Sidebar Entry found in Trash'),
    	'parent_item_colon' => ''
      );

$args = array(
    	'labels' => $labels,
    	'public' => true,
    	'publicly_queryable' => true,
    	'show_ui' => true,
    	'query_var' => true,
    	'rewrite' => true,
    	'capability_type' => 'post',
    	'hierarchical' => true,
    	'menu_position' => null,
    	'supports' => array('title','editor','author', 'page-attributes', 'revisions')
      );

      register_post_type('sidebar-content',$args);

}

?>

In the code we have the function create_post_type which runs at WordPress initialization. Inside the create_post_type function we have the register_post_type function which accepts two arguments: a post type name and an array of arguments ($arg).

I’m not going to go into the details of the register_post_type function or it’s arguments as there is an excellent in depth article by Justin Tadlock explaining the function details.

Most of the values in the $args array are defaults. One exception is the supports argument which defines the post admin features (meta boxes, editors, etc) which will be available for the new post type. Here I only need the title, (WYSIWYG) editor, author, page attributes (parent and order) and revisions boxes. There are many more options so feel free to add more to suit your needs.

Inside the arguments is the $labels array which contains strings that will be used to label the sidebar content admin area.

Screenshot of WordPress admin area for adding new sidebar entry.  Highlighted are the labels defined in the $labels array

Screenshot of WordPress admin area for adding new sidebar entry. Highlighted are the labels defined in the $labels array

2. Create a Template Include File for the Sidebar Content Block

Next we’ll create a new PHP include file which will generate the sidebar content. I’m going to call the file custom-sidebar-content.php and put it in an includes folder for better organization.

<?php 

/* PART 1: Get the page ID and store in $postID variable */ 

$postID = $post->ID;

/* PART 2: For that page, get the 'sidebar-post-id' custom field value */

$sidebarID = get_post_meta($postID, 'sidebar-entry-id', true);

/* PART 3: If a value is returned set up a WP query to retrieve content of Custom sidebar post */

if ($sidebarID) {

    $sidebarEntryArgs = array (

   	 'post_type' => 'sidebar-content',
   	 'post__in' => array ( $sidebarID )

    );

    $sidebarQuery = new WP_Query($sidebarEntryArgs);

    if ( $sidebarQuery->have_posts() ) :

   	 while ( $sidebarQuery->have_posts() ) : $sidebarQuery->the_post();

   		 $sidebarContent = get_the_content();  /* get the content of the post - what ever is in WYSIWYG editor box and store in variable for output below */

   	 endwhile;

    endif;

    wp_reset_query();

}

/* Part 4: Output the sidebar code in a container with classes for CSS */

if ($sidebarContent) {

?>

<div>

   <?php echo $sidebarContent; ?>
   
</div>

<?php } ?>

I have split the code above into 4 parts which are commented.

The first part retrieves the ID of the current WordPress page storing it in the $postID variable.

In the second part we use the page ID to retrieve a custom field value. Each static page which contains custom sidebar content will have a custom field named “sidebar-entry-id”. The value of the custom field will be the ID of the sidebar entry we want to include on the page.

Here we use the get_post_meta function which accepts three parameters. The first is the post ID (in our case the page ID). The second is the custom field name (“sidebar-entry-id” in our case). The third is a boolean value asking if we want to return a single string (true) or an array of custom field values (false). In this case we only want to include one sidebar ID so we will stick with true.

We have now used the page ID to retrieve the sidebar entry ID which we will use to bring in the sidebar entry content to the page.

In the third part of the script we are creating a new WP_Query object to retrieve the associated sidebar entry content. First we check if we have a sidebar ID value returned from get_post_meta function. If so we use the value in the query arguments, $sidebarEntryArgs. In addition to specifying the sidebar entry ID, we also specify the post type which is “sidebar-content”. Within the loop we use the function get_the_content to retrieve the content of the WYSIWYG editor for the sidebar entry and store it in the $sidebarContent variable.

Finally, in part 4, we output the sidebar entry content within a div which has classes for styling the content with CSS. I use the class “CustomSidebar” to style anything specific to the container and the class “entry” to style the contents.

3. Include the new sidebar template file in sidebar.php

The next step is pretty straightforward. Open up sidebar.php or another sidebar file and paste in the following PHP code where the sidebar content will be outputted.

    <?php require_once('includes/custom-sidebar-content.php') ?>

Again, I put the custom-sidebar-content.php file in an includes folder. You may need to adjust the path of the included file.

At this point we have all the architecture for bringing in the sidebar content to the page. In the next two steps well will create some content for a sidebar entry and add it to the sidebar of a specific static page.

4. Create a sidebar entry

Now we need to sign into WordPress and create a sidebar entry. From the dashboard you should see a left menu item called “Sidebar Content” (see figure above). If you click the menu option you will see “Add New”. Clicking on this will bring you to a new entry page.

For this demo we will use the WYSIWYG visual editor to add some simple content: An h3 heading and an unordered list.

Screenshot of the WYSIWYG editor on the example sidebar entry.

Screenshot of the WYSIWYG editor of an example sidebar entry.

You should be able to embed any kind of content including images, video embeds and text of course. You could also dive into the HTML tab and make some more complex widgets.

You can give the entry whatever title you want. It won’t be outputted so I suggest giving it a name which associates it with the page it will be on. For instance, if this was the beer page, I would give it “Beer page sidebar”

Publish the entry and after the page has been reloaded, note down the ID of the sidebar entry as you will need it in the next step. This will be in the URL on the edit page.

The location of the sidebar post ID

Screenshot of the sidebar entry edit page. The entry ID is highlighted in the URL.

View the completed sidebar entry

5. Add the sidebar entry to the WordPress static page

Finally, edit the page which will contain the custom sidebar content. Remember, the page template should have a sidebar.php (or equivalent) which includes custom-sidebar-content.php (step 3).

On the edit page, scroll down to the custom fields box. Under the “name” field, enter “sidebar-entry-id”. In the “value” field enter the sidebar entry ID you noted in the previous step. Click “Add Custom Field” and update the page.

Screenshot of custom fields box on sidebar entry edit page and filled in fields.

Screenshot of custom fields box while editing the static page.

Now if everything worked out the sidebar content should be visible on the static page.

View the example static page with custom sidebar content

Notes

Why I chose Custom Post Types

Custom post types have been around since version 3.0. Since then, I’ve used custom posts to get around a number of problems in WordPress.

I really like how one can tailor the custom post admin to the type of content. For example, instead of having to call a content type a “post” which is far too generic, it can be called “Slide”, “Movie” or “Listing”. Calling a content type something other than post doesn’t really matter to WordPress developers, but it makes a big difference to a client or the person who will be administrating the website.

The website of the non-profit organization I designed this system for also has a blog so I didn’t want entries for sidebar content mixing with the blog items. I realize I could have used a normal post along with a specific category or tag as a filter but I didn’t want to have to modify the queries on the index.php, archives.php, and other archive pages. Using a custom post type automatically excludes it from the blog post listing. Also, adding the category or tag is another step in the process of creating a sidebar entries. I wanted to keep it as simple as possible.

Limitations

As I mentioned this demo is tailored to adding custom sidebar content to static pages. However, I will try to eventually make the code more general so single post pages and other archive pages can have custom sidebar content. In the meantime, please feel free to extend the technique.

Generation of Custom Post Types

It should be known that plugins exist which make it easier to register custom post types such as Custom Post Type UI by Brad Williams

blog comments powered by Disqus