使用自定义帖子类型填充自动完成字段

时间:2017-01-21 作者:geektripp

好的,我创建了一个自定义的帖子类型,叫做“视频游戏”我还有一个自动完成字段的脚本。我想做两件事:

我希望源是视频游戏帖子类型和标题中的特色图像。

我还需要它来存储他们单击时的答案,以便我可以在他们的个人资料中调用它。

最后,我需要他们能够选择尽可能多的答案。如果有人能帮我做这三件事,我将不胜感激!脚本的代码如下:

   <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet"     href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">

<script>
$( "#autocomplete" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"     ]
});
</script>

</body>
</html>

1 个回复
最合适的回答,由SO网友:Pedro Coitinho 整理而成

你的问题很复杂,但让我们试一试吧!

我最近上了一堂课,我很乐意与大家分享。

这并不是一个完整的回答,但它将为您提供大部分帮助。

您需要知道的是WP执行ajax的奇怪方式,这涉及到在Wordpress ajax端点注册操作。

class YOURCPT_autocomplete {

  /**
  * Constructor
  */
  public function __construct() {
    // add actions on construct
    add_action( \'wp_enqueue_scripts\', array( $this, \'enqueue_scripts\' ), 5 );

    // And these two actions are the ajax search actions
    // we use the hook wp_ajax_{action} to define our ajax action
    // here we defined the \'search\' action
    // for both logged in and out users
    // in your case you probably dont need the \'nopriv\' hook, for logged out users
    add_action( \'wp_ajax_search\', array( $this, \'ajax_search\' ) );
    add_action( \'wp_ajax_nopriv_search\', array( $this, \'ajax_search\' ) );

    // in all of the cases above we call a method of this same class:
    // array( $this, \'your_function_name\' );
  }

  /**
  * Register scripts
  */
  public function enqueue_scripts() {

    // enqueue JS and CSS. 
    // You will have to change these next two lines to point to your own
    wp_enqueue_style( \'autocomplete\', YOURTHEME_OR_PLUGIN_BASE . \'/YOUR.css\' );
    wp_enqueue_script( \'autocomplete\', YOURTHEME_OR_PLUGIN_BASE . \'/js/YOUR.js\', array( \'jquery-ui-autocomplete\' ), \'true\', true );

    // then we get a reference to the ajax endpoint using wp_localize script
    // this will create a variable called `opts` which has a member
    // `ajax_url` which, you guessed, has the ajax url.
    wp_localize_script( \'autocomplete\', \'opts\', array(
      \'ajax_url\' => admin_url( \'admin-ajax.php\' ) )
    );
  }

  /**
  * Ajax - this is the function that searches CPTs
  */
  public function ajax_search() {
    // we send ajax request to ajax_url

    // check for term, if doesnt exist die
    if ( empty( $_REQUEST[\'term\'] ) ) {
        wp_die();
    }

    // WP Query arguments
    // we get the \'term\' from the ajax call, clean it and make a search
    $args = array(
      \'s\'         => trim( esc_attr( strip_tags( $_REQUEST[\'term\'] ) ) ),
      \'post_type\' => \'YOURCPT\'
    );

    // array to keep results
    $results = array();

    // make a query 
    $query = new WP_Query( $args );

    // save results
    // formatted with the title as \'label\' for the autocomplete script 
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
          $query->the_post();
          $results[] = array(
              \'label\'     => esc_html( get_the_title() ),    // title
              \'link\'      => get_permalink(),                // link
              \'id\'        => get_the_ID(),                   // id
               // and whatever eles you want to send to the front end
          );
        }
    }

    // echo results
    echo json_encode($results);

    // kill process
    // all ajax actions in WP need to die when they are done!
    wp_die();
  }

}
接下来是JS(将跳过css)

jQuery( function ($) {

  // create an jq-ui autocomplete on your selected element
  $( \'WHICHEVER_ELEMENT_WILL_USE_AUTOCOMPLETE\' ).autocomplete( {
    // use a function for its source, which will return ajax response
    source: function(request, response){

      // well use opts.ajax_url which we enqueued with WP
      $.post( opts.ajax_url, {
            action: \'search\',            // our action is called search
            term: request.term           // and we get the term com jq-ui
        }, function(data) {
          // when we get data from ajax, we pass it onto jq-ui autocomplete
          response(data);
        }, \'json\'
      );
    },
    // next, is the select behaviour
    // on select do your action
    select: function(evt, ui) {
      evt.preventDefault();

      // here you can call another AJAX action to save the option
      // or whatever

    },
  } );
} ( jQuery ) );
酷!现在只需在函数中创建类。php,它将为您排队。

// include the file where you have your class, if not in your functions.php
include( \'path/to/the/class/YOURCPT_autocomplete.php\' );

// instantiate the class
new YOURCPT_autocomplete();
完成!

您可以有条件地执行最后一步,并且只在某些页面、帖子类型等中包含它。

要保存所选选项,可以使用上面类中的挂钩创建另一个ajax操作。

您的处理功能可以使用update_user_meta 使用条款

最后,要使用多个值,您应该看看jQuery ui文档。您完全可以做到:https://jqueryui.com/resources/demos/autocomplete/multiple.html

如果您想获得有关这些精巧的wordpress功能的好教程,我肯定会推荐smashingmag:https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/

希望你能有个好的开始!