Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress custom metabox input value with AJAX

I am using Wordpress 3.5, I have a custom post (sp_product) with a metabox and some input field. One of those input (sp_title).

I want to Search by the custom post title name by typing in my input (sp_title) field and when i press add button (that also in my custom meta box), It will find that post by that Title name and bring some post meta data into this Meta box and show into other field.

enter image description here

Here in this picture (Example)

  1. Search
  2. Click Button
  3. Get some value by AJAX from a custom post.

Please give me a example code (just simple)

  1. I will search a simple custom post Title,
  2. Click a button
  3. Get the Title of that post (that i search or match) with any other post meta value, By AJAX (jQuery-AJAX).

Please Help me.

like image 962
zxprince Avatar asked Oct 06 '22 07:10

zxprince


1 Answers

I was able to find the lead because one of my plugins uses something similar to Re-attach images.
So, the relevant Javascript function is findPosts.open('action','find_posts').

It doesn't seem well documented, and I could only found two articles about it:

  • Find Posts Dialog Box
  • Using Built-in Post Finder in Plugins

Tried to implement both code samples, the modal window opens but dumps a -1 error. And that's because the Ajax call is not passing the check_ajax_referer in the function wp_ajax_find_posts.

So, the following works and it's based on the second article. But it has a security breach that has to be tackled, which is wp_nonce_field --> check_ajax_referer. It is indicated in the code comments.
To open the Post Selector, double click the text field.
The jQuery Select needs to be worked out.

Plugin file

add_action( 'load-post.php', 'enqueue_scripts_so_14416409' );
add_action( 'add_meta_boxes', 'add_custom_box_so_14416409' );
add_action( 'wp_ajax_find_posts', 'replace_default_ajax_so_14416409', 1 );

/* Scripts */
function enqueue_scripts_so_14416409() {
  # Enqueue scripts
  wp_enqueue_script( 'open-posts-scripts', plugins_url('open-posts.js', __FILE__), array('media', 'wp-ajax-response'), '0.1', true );

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

/* Meta box create */
function add_custom_box_so_14416409() 
{
    add_meta_box( 
        'sectionid_so_14416409',
        __( 'Select a Post' ),
        'inner_custom_box_so_14416409',
        'post' 
    );
}

/* Meta box content */
function inner_custom_box_so_14416409( $post ) 
{
    ?>
    <form id="emc2pdc_form" method="post" action="">
        <?php wp_nonce_field( 'find-posts', '_ajax_nonce', false); ?> 
        <input type="text" name="kc-find-post" id="kc-find-post" class="kc-find-post">
    </form>
    <?php
}

/* Ajax replacement - Verbatim copy from wp_ajax_find_posts() */
function replace_default_ajax_so_14416409()
{
    global $wpdb;

    // SECURITY BREACH
    // check_ajax_referer( '_ajax_nonce' );

    $post_types = get_post_types( array( 'public' => true ), 'objects' );
    unset( $post_types['attachment'] );

    $s = stripslashes( $_POST['ps'] );
    $searchand = $search = '';
    $args = array(
        'post_type' => array_keys( $post_types ),
        'post_status' => 'any',
        'posts_per_page' => 50,
    );
    if ( '' !== $s )
        $args['s'] = $s;

    $posts = get_posts( $args );

    if ( ! $posts )
        wp_die( __('No items found.') );

    $html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>'.__('Title').'</th><th class="no-break">'.__('Type').'</th><th class="no-break">'.__('Date').'</th><th class="no-break">'.__('Status').'</th></tr></thead><tbody>';
    foreach ( $posts as $post ) {
        $title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' );

        switch ( $post->post_status ) {
            case 'publish' :
            case 'private' :
                $stat = __('Published');
                break;
            case 'future' :
                $stat = __('Scheduled');
                break;
            case 'pending' :
                $stat = __('Pending Review');
                break;
            case 'draft' :
                $stat = __('Draft');
                break;
        }

        if ( '0000-00-00 00:00:00' == $post->post_date ) {
            $time = '';
        } else {
            /* translators: date format in table columns, see http://php.net/date */
            $time = mysql2date(__('Y/m/d'), $post->post_date);
        }

        $html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-'.$post->ID.'" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>';
        $html .= '<td><label for="found-'.$post->ID.'">' . esc_html( $title ) . '</label></td><td class="no-break">' . esc_html( $post_types[$post->post_type]->labels->singular_name ) . '</td><td class="no-break">'.esc_html( $time ) . '</td><td class="no-break">' . esc_html( $stat ). ' </td></tr>' . "\n\n";
    }

    $html .= '</tbody></table>';

    $x = new WP_Ajax_Response();
    $x->add( array(
        'data' => $html
    ));
    $x->send();
}

Javascript file open-posts.js

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() {
    $findBox.data('kcTarget', $(this));
    findPosts.open();
  });

  // Insert
  $findBoxSubmit.click(function(e) {
    e.preventDefault();

    // Be nice!
    if ( !$findBox.data('kcTarget') )
      return;

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

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

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

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

  // Close
  $( '#find-posts-close' ).click(function() {
    $findBox.removeData('kcTarget');
  });
});
like image 64
brasofilo Avatar answered Oct 10 '22 02:10

brasofilo