Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to set up a sidebar area that'll do two things:

  1. Display a drop-down of posts in a given custom post types.
  2. Display post metadata (content and custom fields) if selected post

The thing that's getting me is two-fold:

  1. Having the selected post metadata display in the sidebar once selected via the dropdown
  2. Having the content refresh via ajax or jquery so it doesn't refresh the entire page
share|improve this question
    
Can you clarify what you mean by "Having the 'select' button bring up the data in the sidebar" and you say you want to "Display post data based on selection in #1"; what data? A list of post titles, or other? A post type has many posts. –  MikeSchinkel Nov 13 '10 at 0:14
    
@MikeSchinkel my mistake. I realized how poorly worded my question was. I've edited it. –  Norcross Nov 13 '10 at 5:35

1 Answer 1

up vote 3 down vote accepted

Hi @Norcross:

What you are looking for is a bit involved but I wrote it anyway. Unfortunately it took longer than I planned so I've run out of gas on going in depth to explain it but I did document the code so hopefully that will help you follow it and you can download a copy of the code here.

The Widget in Use on the Website:

WordPress Widget showing a Dropdown List of Posts

Note in my example I wrote a generic function to grab all the meta keys and meta values associated with a post to have something to display; that's what you see on the screen.

The Widget Configuration in the Admin Console:

Screenshot of WordPress Widgets Admin Screen

The Code

Here's the code. This can be used in your theme's functions.php file or as a standalone file in a plugin or theme you are developing:

<?php
/*
Plugin Name: List_Custom_Post_Type_Posts_with_AJAX class
Version: 0.1
Author: Mike Schinkel
Author URI: http://mikeschinkel.com

  Shows how to create a widget with a dropdown list of posts for a given post type 
  and then retrieve HTML specific to the selected post via AJAX to insert into the         
  page.

  Yes, the name of the class is insanely long in hopes that you'll be forced to 
  think about what would be a better name.

  This can be used in your theme's functions.php file or as a standalone file in a
  plugin or theme you are developing.

*/

class List_Custom_Post_Type_Posts_with_AJAX extends WP_Widget {
  /*
   * List_Custom_Post_Type_Posts_with_AJAX() used by the Widget API 
   * to initialize the Widget class
   */
  function List_Custom_Post_Type_Posts_with_AJAX() {
    $this->WP_Widget(
      'list-custom-post-type-posts-with-ajax',
      'List Custom Post Type Posts with AJAX',
      // Widget Settings
      array(
        'classname' => 'list-custom-post-type-posts-with-ajax',
        'description' => 'Widget to List List Custom Post Type Posts with AJAX.',
      ),
      // Widget Control Settings
      array(
        'height' => 250,  // Set the form height (doesn't seem to do anything)
        'width'  => 300,  // Set the form width
        'id_base' => 'list-custom-post-type-posts-with-ajax',
      )
    );
  }
  /*
   * widget() used by the Widget API to display a form in the widget area of the admin console
   *
   */
  function form( $instance ) {
    global $wp_post_types;
    $instance = self::defaults($instance);  // Get default values

    // Build the options list for our select
    $options = array();
    foreach($wp_post_types as $post_type) {
      if ($post_type->publicly_queryable) {
        $selected_html = '';
        if ($post_type->name==$instance['post_type']) {
          $selected_html = ' selected="true"';
          $post_type_object = $post_type;
        }
        $options[] = "<option value=\"{$post_type->name}\"{$selected_html}>{$post_type->label}</option>";
      }
    }
    $options = implode("\n",$options);

    // Get form attributes from Widget API convenience functions
    $title_field_id = $this->get_field_id( 'title' );
    $title_field_name = $this->get_field_name( 'title' );
    $post_type_field_id = $this->get_field_id( 'post_type' );
    $post_type_field_name = $this->get_field_name( 'post_type' );

    // Get HTML for the form
    $html = array();
    $html = <<<HTML
<p>
  <label for="{$post_type_field_id}">Post Type:</label>
  <select id="{$post_type_field_id}" name="{$post_type_field_name}">
    {$options}
  </select>
</p>
<p>
  <label for="{$title_field_id}">Label:</label>
  <input type="text" id="{$title_field_id}" name="{$title_field_name}"
      value="{$instance['title']}" style="width:90%" />
</p>
HTML;
    echo $html;
  }
  /*
   * widget() used by the Widget API to display the widget on the external site
   *
   */
  function widget( $args, $instance ) {
    extract( $args );
    $post_type = $instance['post_type'];
    $dropdown_name = $this->get_field_id( $post_type );
    // jQuery code to response to change in drop down
    $ajax_url = admin_url('admin-ajax.php');
    $script = <<<SCRIPT
<script type="text/javascript">
jQuery( function($) {
  var ajaxurl = "{$ajax_url}";
  $("select#{$dropdown_name}").change( function() {
    var data = {
      action: 'get_post_data_via_AJAX',
      post_id: $(this).val()
    };
    $.post(ajaxurl, data, function(response) {
      if (typeof(response)=="string") {
        response = eval('(' + response + ')');
      }
      if (response.result=='success') {
        if (response.html.length==0) {
          response.html = 'Nothing Found';
        }
        $("#{$dropdown_name}-target").html(response.html);
      }
    });
    return false;
  });
});
</script>
SCRIPT;
    echo $script;
    echo $before_widget;
    if ( $instance['title'] )
       echo "{$before_title}{$instance['title']}{$after_title}";

    global $wp_post_types;
    // Dirty ugly hack because get_pages() called by wp_dropdown_pages() ignores non-hierarchical post types
    $hierarchical = $wp_post_types[$post_type]->hierarchical;
    $wp_post_types[$post_type]->hierarchical = true;

    // Show a drop down of post types
    wp_dropdown_pages(array(
      'post_type'   => $post_type,
      'name'        => $dropdown_name,
      'id'          => $dropdown_name,
      'post_status' => ($post_type=='attachment' ? 'inherit' : 'publish'),
    ));

    $wp_post_types[$post_type]->hierarchical = $hierarchical;

    echo $after_widget;

    // Create our post html target for jQuery to fill in
    echo "<div id=\"{$dropdown_name}-target\"></div>";

  }
  /*
   * update() used by the Widget API to capture the values for a widget upon save.
   *
   */
  function update( $new_instance, $old_instance ) {
    return $this->defaults($new_instance);
  }
  /*
   * defaults() conveninence function to set defaults, to be called from 2 places
   *
   */
  static function defaults( $instance ) {
    // Give post_type a default value
    if (!get_post_type_object($instance['post_type']))
      $instance['post_type'] = 'post';

    // Give title a default value based on the post type
    if (empty($instance['title'])) {
      global $wp_post_types;
      $post_type_object = $wp_post_types[$instance['post_type']];
      $instance['title'] = "Select a {$post_type_object->labels->singular_name}";
    }
    return $instance;
  }
  /*
   * self::action_init() ensures we have jQuery when we need it, called by the 'init' hook
   *
   */
  static function action_init() {
    wp_enqueue_script('jquery');
  }
  /*
   * self::action_widgets_init() registers our widget when called by the 'widgets_init' hook
   *
   */
  static function action_widgets_init() {
    register_widget( 'List_Custom_Post_Type_Posts_with_AJAX' );
  }
  /*
   * self::get_post_data_via_AJAX() is the function that will be called by AJAX
   *
   */
  static function get_post_data_via_AJAX() {
    $post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
    $html = self::get_post_data_html($post_id);
    $json = json_encode(array(
      'result'  => 'success',
      'html'    => $html,
    ));
    header('Content-Type:application/json',true,200);
    echo $json;
    die();
  }
  /*
   * self::on_load() initializes our hooks
   *
   */
  static function on_load() {
    add_action('init',array(__CLASS__,'action_init'));
    add_action('widgets_init',array(__CLASS__,'action_widgets_init'));

    require_once(ABSPATH."/wp-includes/pluggable.php");
    $user = wp_get_current_user();
    $priv_no_priv = ($user->ID==0 ? '_nopriv' : '');
    add_action("wp_ajax{$priv_no_priv}_get_post_data_via_AJAX",array(__CLASS__,'get_post_data_via_AJAX'));
  }
  /*
   *  get_post_data_html($post_id)
   *
   *    This is the function that generates the HTML to send back to the client
   *    Below is a generic want to list post meta but you'll probably want to
   *    write custom code and use the outrageously long named hook called:
   *
   *      'html-for-list-custom-post-type-posts-with-ajax'
   *
   */
  static function get_post_data_html($post_id) {
    $html = array();
    $html[] = '<ul>';
    foreach(get_post_custom($post_id) as $name => $value) {
      $html[] = "<li>{$name}: {$value[0]}</li>";
    }
    $html[] = '</ul>';
    return apply_filters('html-for-list-custom-post-type-posts-with-ajax',implode("\n",$html));
  }
}
// This sets the necessary hooks
List_Custom_Post_Type_Posts_with_AJAX::on_load();

Also, if you want to read a good article about coding Widgets, Justin Tadlock has a good one called:

share|improve this answer
    
Perfect. Once the little one goes down for a nap, I'll test it out completely. I've made a handful of plugins and widgets before, it was the AJAX part that was throwing me for a loop. –  Norcross Nov 13 '10 at 15:31
    
@Mike There's something I am missing (I removed my previous comment). When I add this as a plug-in, it doesn't seem to work for posts or custom post types. However, when pages are selected, it seems to function just fine. –  Norcross Nov 13 '10 at 16:40
    
@Norcross - What other plugins do you have? Could they be mess with the query to cause this to fail? Any when you say "it doesn't seem to work for posts or custom post types" can you tell me exactly what it is that it is doing wrong, or not doing? –  MikeSchinkel Nov 14 '10 at 0:52
    
@Norcross - In an effort to proactively guess at your problem, if the drop down is not working, add an echo $post_type; exit; just before wp_dropdown_pages() to see what the value of $post_type is. It is it correct and you are not getting a drop down then another plugin is messing with wp_dropdown_pages(). –  MikeSchinkel Nov 14 '10 at 0:55
    
@Mike thanks for the suggestion. When adding the echo $post_type, it displays the selection made in the widget settings, however, no other information displays after that in the entire sidebar. Here's a rundown of the current status: 1. When "Pages" are selected, the dropdown works perfectly. 2. When "Posts" are selected, nothing appears below the H3 tag At the current moment I have no other plugins activated at all. –  Norcross Nov 14 '10 at 5:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.