Using Built-in Post Finder in Plugins


I was making some improvements to the KC Posts widget module in my KC Essentials plugin, and I wanted to make it easy for the users to find post IDs they want to include/exclude from the query. As you may already know, in the Media admin page, we can ‘attach’ an attachment to a post. It uses a neat jQuery UI dialog box to find posts. Here’s how I use it in KC Essentials.

First add we need to add the dialog box and the required JS to the admin page, in my case, it’s widgets.php.

add_action( 'load-widgets.php', 'my_widgets_admin_actions' );
function my_widgets_admin_actions() {
  # Enqueue scripts
  wp_enqueue_script( 'my-widgets-admin-scripts', plugins_url('myscript.js', __FILE__), array('media', 'wp-ajax-response'), '0.1', true );

  # Add the finder dialog box
  add_action( 'admin_footer', 'find_posts_div', 99 );

Next, create myscript.js file inside the plugin directory and add these lines:

jQuery(document).ready(function($) {
  // Find posts
  var $findBox = $('#find-posts'),
      $found   = $('#find-posts-response'),
      $findBoxSubmit = $('#find-posts-submit');

  // Open
  $('input.kc-find-post').live('dblclick', function() {
    $'kcTarget', $(this));;

  // Insert
  $ {

    // Be nice!
    if ( !$'kcTarget') )

    var $selected = $found.find('input:checked');
    if ( !$selected.length )
      return false;

    var $target = $'kcTarget'),
        current = $target.val(),
        current = current === '' ? [] : current.split(','),
        newID   = $selected.val();

    if ( $.inArray(newID, current) < 0 ) {
      $target.val( current.join(',') );

  // Double click on the radios
  $('input[name="found_post_id"]', $findBox).live('dblclick', function() {

  // Close
  $( '#find-posts-close' ).click(function() {

A quick explanation:
When the user double-clicks the input.kc-find-post field, the finder dialog box will popup. Clicking the Select button will send the selected post's ID to the input field. This can also be done by double-clicking one of the radio inputs at the left side of each found posts.

Need a demo? Just install KC Essentials :)

One thought on “Using Built-in Post Finder in Plugins

  1. LucaRosaldi

    Hi there, great article!
    I followed your instructions and the dialog box opens correctly, but for some reason there are no radio buttons, and the search does not work, as it always returns a “-1″. I’m on WordPress 3.5.
    Do you have any clue about why does this happen? Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>