bestsource

AJAX와 함께 워드프레스 사용자 지정 메타박스 입력값

bestsource 2023. 10. 11. 20:51
반응형

AJAX와 함께 워드프레스 사용자 지정 메타박스 입력값

저는 워드프레스 3.5를 사용하고 있고, 메타박스와 약간의 입력 필드가 있는 커스텀 포스트(sp_product)가 있습니다.입력(sp_title) 중 하나입니다.

내 입력(sp_title) 필드에 입력하여 사용자 지정 게시물 제목 이름으로 검색하고 추가 버튼(사용자 지정 메타 상자에도 있음)을 누르면 해당 제목 이름으로 해당 게시물을 찾고 일부 게시물 메타 데이터를 이 메타 상자로 가져와 다른 필드에 표시합니다.

enter image description here

이 사진의 여기(예)

  1. 서치
  2. 클릭버튼
  3. 사용자 지정 게시물에서 AJAX의 값을 가져옵니다.

예제 코드를 주세요(단순히)

  1. 간단한 사용자 지정 게시물 제목을 검색해 보겠습니다.
  2. 버튼 클릭
  3. 다른 게시물 메타 값인 AJAX(jQuery-AJAX)와 함께 해당 게시물의 제목(검색 또는 일치)을 가져옵니다.

제발 도와주세요.

제 플러그인 중 하나가 이미지 재첨부와 유사한 것을 사용하기 때문에 리드를 찾을 수 있었습니다.
그래서 관련된 자바스크립트 함수는findPosts.open('action','find_posts').

문서화가 잘 되어있지 않은 것 같고, 두 개의 기사만 찾을 수 있었습니다.

두 코드 샘플을 모두 구현하려고 하면 modal 창이 열리지만 dump a-1오류. 그리고 그것은 아약스의 전화가 전달되지 않기 때문입니다.check_ajax_referer그 기능에 있어서

그래서 다음과 같은 내용이 있고 두 번째 글을 토대로 합니다.하지만 보안 위반은 해결해야 할 문제인데요.wp_nonce_field --> check_ajax_referer. 코드 주석에 표시되어 있습니다.
게시물 선택기를 열려면 텍스트 필드를 두 번 클릭합니다.
jQuery 문제를 해결해야 합니다.

플러그인 파일

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();
}

자바스크립트 파일

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');
  });
});

언급URL : https://stackoverflow.com/questions/14416409/wordpress-custom-metabox-input-value-with-ajax

반응형