FriendlyWP
11/23/2012 - 6:15 PM

Posts 2 Posts List Widget

Posts 2 Posts List Widget

<?php
/*
Plugin Name: Posts 2 Posts List Widget
Plugin URI: http://friendlywebconsulting.com/
Description: Creates a widget to display posts connected via the Posts 2 Posts plugin by Scribu, found here: http://wordpress.org/extend/plugins/posts-to-posts/ 
Author: Michelle McGinnis
Author URI: http://friendlywebconsulting.com/
Version: 1.0.0-alpha
*/

class PostsToPostsListWidget extends WP_Widget
{
  function PostsToPostsListWidget()
  {
    $widget_ops = array('classname' => 'PostsToPostsListWidget', 'description' => 'Displays linked posts linked via the Posts 2 Posts Plugin.' );
    $this->WP_Widget('PostsToPostsListWidget', 'Posts to Posts List Widget', $widget_ops);
  }
 
function form($instance) {
    global $wpdb;
    $prefix = $wpdb->prefix;
    $mkm_p2p_db_lookups = $wpdb->get_results("SELECT DISTINCT p2p_type, fromtype.post_type AS fromtype,  totype.post_type AS totype from " . $prefix . "p2p inner join " . $prefix . "posts as fromtype ON " . $prefix . "p2p.p2p_from = fromtype.ID inner join " . $prefix . "posts as totype ON " . $prefix . "p2p.p2p_to = totype.ID");

    $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'mkm_parent_type' => '', 'mkm_child_type' => '', 'mkm_p2p_connection_type' => '' ) );
    $title = $instance['title'];
    $mkm_parent_type = $instance['mkm_parent_type'];
    $mkm_child_type = $instance['mkm_child_type'];
    $mkm_p2p_connection_type = $instance['mkm_p2p_connection_type'];
  ?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
  <p><label for="<?php echo $this->get_field_id('mkm_p2p_connection_type'); ?>">P2P Connection Type: 
  <select id="<?php echo $this->get_field_id('mkm_p2p_connection_type'); ?>" class="conn_type" name="<?php echo $this->get_field_name('mkm_p2p_connection_type'); ?>" class="widefat" style="width:100%;">
    <?php $myFieldID = $this->get_field_id('mkm_p2p_connection_type'); ?>
    <?php
    // LOOP THROUGH THE CONNECTION TYPES AND PUT THE TO AND FROM POST TYPE OPTIONS FOR 
    // EACH CONNECTION TYPE IN THEIR OWN ARRAY
    $i=0;
    foreach ($mkm_p2p_db_lookups as $p2p_db_lookup) { 
        $name = $p2p_db_lookup->p2p_type;
        $totype = $p2p_db_lookup->totype;
        $fromtype = $p2p_db_lookup->fromtype;
        // LOOP THROUGH THE "TO" TYPES AND THE "FROM" TYPES AND CONCATENATE THEM IN THE "PARENT" DROPDOWN
        // This allows users to select in either direction
        $to_optionlist = '<option ' . selected( $instance['mkm_parent_type'], $totype ) . ' value="' . $totype . '">' . $totype . '</option>' . '<option ' . selected( $instance['mkm_child_type'], $totype ) . ' value="' . $fromtype . '">' . $fromtype . '</option>'; 
        // LOOP THROUGH THE "FROM" TYPES AND THE "TO" TYPES AND CONCATENATE THEM IN THE "CHILD" DROPDOWN
        // This allows users to select in either direction
        $from_optionlist = '<option ' . selected( $instance['mkm_parent_type'], $fromtype ) . ' value="' . $totype . '">' . $totype . '</option>' . '<option ' . selected( $instance['mkm_child_type'], $fromtype ) . ' value="' . $fromtype . '">' . $fromtype . '</option>'; 
        // GIVE A NUMBER TO THE ARRAYS SO THEY'LL BE AVAILABLE WHEN NEEDED
        $to_optionarrays[$i] = $to_optionlist;
        $from_optionarrays[$i] = $from_optionlist;
    ?>
        <!-- OUTPUT THE CONNECTION TYPE DROPDOWN -->
        <option <?php selected( $instance['mkm_p2p_connection_type'], $name ); ?> value="<?php echo $name; ?>"><?php echo $name; ?></option>
    <?php $i++; } ?>      
  </select></p>

  <p><label for="<?php echo $this->get_field_id('mkm_parent_type'); ?>">Parent Post Type: 
  <?php 
    // LOOP THROUGH THE CONNECTION TYPES AND OUTPUT THE PARENT ('T0+FROM') POST TYPES FOR EACH.
    // THESE WILL THEN BE HIDDEN/SHOWN VIA JQUERY.
    $i=0;
    foreach ($to_optionarrays as $to_optionarray) { ?>
      <select id="<?php echo $this->get_field_id('mkm_parent_type') . '-' . $i; ?>" class="<?php echo ' p_select' . $i; ?>" name="<?php echo $this->get_field_name('mkm_parent_type'); ?>" class="widefat" style="width:100%;">
        <!-- OUTPUT THE "TO" POST TYPE OPTION ARRAY -->
       <?php echo $to_optionarray; ?>
      </select>
    <?php $i++;
    } ?>      
  </p>

  <p><label for="<?php echo $this->get_field_id('mkm_child_type'); ?>">Child Post Type: 
  <?php 
    // LOOP THROUGH THE CONNECTION TYPES AND OUTPUT THE CHILD ('TO+FROM') POST TYPES FOR EACH.
    // THESE WILL THEN BE HIDDEN/SHOWN VIA JQUERY.
    $i=0;
    foreach ($from_optionarrays as $from_optionarray) { ?>
      <select id="<?php echo $this->get_field_id('mkm_child_type') . '-' . $i; ?>" class="<?php echo ' c_select' . $i; ?>" name="<?php echo $this->get_field_name('mkm_child_type'); ?>" class="widefat" style="width:100%;">
        <!-- OUTPUT THE "FROM" POST TYPE DROPDOWN -->
       <?php echo $from_optionarray; ?>
      </select>
    <?php $i++;
    } ?>      
  </p>

  <script type="text/javascript">
    jQuery(function( $ ) {

      // GET THE ORIGINAL PHP DB LOOP AND MAKE READABLE BY JQUERY VIA JSON
      var p2p_db_lookups = <?php echo json_encode($mkm_p2p_db_lookups); ?>;
      
      // HIDE & DISABLE ALL THE PARENT/CHILD POST TYPE SELECT FIELDS
      $.each(p2p_db_lookups, function (i, elem) {
          $('select.p_select'+i).hide();
          $('select.p_select'+i).attr('disabled', 'disabled');
          $('select.c_select'+i).hide();
          $('select.c_select'+i).attr('disabled', 'disabled');         
      });

      // FIND THIS FORM'S P2P CONNECTION TYPE SELECT FIELD BY ID, AND AS IT CHANGES,
      // FIND THE CORRESPONDING PARENT/CHILD POST TYPE SELECTS AND SHOW/ENABLE THEM,
      // WHILE KEEPING THEIR SIBLINGS HIDDEN/DISABLED.
      $('[id$="-mkm_p2p_connection_type"]').change(function(){
          var thisform = $(this).closest('form');
          thisform.find("select.p_select" + this.selectedIndex).show().siblings().hide();
          thisform.find("select.p_select" + this.selectedIndex).removeAttr('disabled');
          thisform.find("select.c_select" + this.selectedIndex).show().siblings().hide();
          thisform.find("select.c_select" + this.selectedIndex).removeAttr('disabled');
      });
      $('[id$="-mkm_p2p_connection_type"]').change();

      // SEE http://wordpress.stackexchange.com/a/37707/16
      // THIS ENABLES THE ABOVE TO WORK AFTER THE WIDGET(S) ARE DRAGGED-AND-DROPPED
      // INSTEAD OF ONLY AFTER THEY ARE SAVED:
      $('#widgets-right').ajaxComplete(function(event, XMLHttpRequest, ajaxOptions){

        // determine which ajax request is this (we're after "save-widget")
        var request = {}, pairs = ajaxOptions.data.split('&'), i, split, widget;

        for(i in pairs){
          split = pairs[i].split('=');
          request[decodeURIComponent(split[0])] = decodeURIComponent(split[1]);
        }

        // only proceed if this was a widget-save request
        if(request.action && (request.action === 'save-widget')){
          $('[id$="-mkm_p2p_connection_type"]').change(function(){
              var thisform = $(this).closest('form');
              thisform.find("select.p_select" + this.selectedIndex).show().siblings().hide();
              thisform.find("select.p_select" + this.selectedIndex).removeAttr('disabled');
              thisform.find("select.c_select" + this.selectedIndex).show().siblings().hide();
              thisform.find("select.c_select" + this.selectedIndex).removeAttr('disabled');
          });
          $('[id$="-mkm_p2p_connection_type"]').change();
        }

      });

  });
  </script>

<?php
  } // END FORM FUNCTION
 
  function update($new_instance, $old_instance)
  {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    $instance['mkm_parent_type'] = $new_instance['mkm_parent_type'];
    $instance['mkm_child_type'] = $new_instance['mkm_child_type'];
    $instance['mkm_p2p_connection_type'] = $new_instance['mkm_p2p_connection_type'];
    return $instance;
  }
 
  function widget($args, $instance)
  {

    extract($args, EXTR_SKIP);
 
    echo $before_widget;
    $title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
    $mkm_parent_type = empty($instance['mkm_parent_type']) ? ' ' : $instance['mkm_parent_type'];
    $mkm_child_type = empty($instance['mkm_child_type']) ? ' ' : $instance['mkm_child_type'];
    $mkm_p2p_connection_type = empty($instance['mkm_p2p_connection_type']) ? ' ' : $instance['mkm_p2p_connection_type'];
    
    if (!empty($title)) {
      echo $before_title . $title . $after_title;
    }

    $mkm_widget_query = new WP_Query( array(
      'post_type' => $mkm_parent_type,
      'nopaging' => true,
      'order' => 'ASC',
      'orderby' => 'menu_order',
    ) );
    
    p2p_type( $mkm_p2p_connection_type )->each_connected( $mkm_widget_query, array(), $mkm_child_type );
    
    while ( $mkm_widget_query->have_posts() ) : $mkm_widget_query->the_post();
   		global $post; ?>

	    <h5><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h5>
	    	<ul>
	    <?php 

	    // Display connected books
			foreach ( $post->$mkm_child_type as $post ) : setup_postdata( $post ); ?>
				<li><a href="<?php echo get_post_permalink(); ?>"><?php the_title(); ?></a></li>
	 		<?php endforeach; ?>
	 		</ul>
    <?php
    	 		wp_reset_postdata();
    	endwhile;

  echo $after_widget;
  }
 
}
add_action( 'widgets_init', create_function('', 'return register_widget("PostsToPostsListWidget");') );

?>