Tuesday, February 8, 2011

How to add different custom content on WordPress pages

In the last few months I had to work on different WordPress sites which required different content on different pages. That content was supposed to be manageable from WordPress administrator account. As I was new to WordPress I decided to create a plugin each time I needed manageable content to appear on different pages. This morning I just figured out how to take advantage of some already made WordPress plugins which would make this task much easier and much efficient, from my point of view.

Let's take the example of adding different Sidebars on each page of a site.
1. The plugin I am using is Custom Post Type UI. After installing and activating it I define my custom type Sidebars. From plugin's Advanced Options I choose it to support Title, Editor and Custom Fields. I also define a taxonomy for this custom type, called Page Sidebars and I attach it to Post Type pages.



2. Now in Dashboard I have a new option to administrate the custom type I just defined. So all I have to do is to go to Sidebars and start adding new content of this type.


3. When I insert new pages in the left of the editing window I can add the custom types by their title.


4. Now the code I use in sidebar.php from my theme to get for each page the content of each custom type sidebar related to each page.
/* get the global post variable to know on what page you are on */
global $post;
/* for the given page, get the taxonomies of type page_sidebars */
$data          = get_the_terms($post->ID, 'page_sidebars');
$my_sidebars   = array();
foreach($data as $sidebar):
/* get the post of type sidebars with the name of the page_sidebars taxonomy */
$my_sidebars[] = get_post_by_name($sidebar->slug, 'sidebars');
endforeach;


In functions.php of your theme define
function get_post_by_name($page_name, $post_type = 'post', $output = OBJECT) {
   global $wpdb;
   $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_name, $post_type ));
   if ( $post )
      return get_post($post, $output);

   return null;
}
Note: If you need new fields for your custom types, there is another plugin easy to use and integrate with Custom Types UI: Custom Field Template

No comments: