1

Okay, so I have created a custom post type called "Video Games." I also have the script for an autocomplete field. I'm wanting to do 2 things:

I want the source to be the featured image from the Video Games post type and the title.

I also need for it to store the answer when they click it so I can call it in their profiles.

Lastly, I need for them to be able to select as many answers as they can. If someone can help me with these 3 things, I'd be INCREDIBLY grateful! The code for the script is below:

   <!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
  • aww I was just reading your post when it got deleted. If you're willing to share what you have, I truly will be appreciative. If not, I understand. I do know it's a lot to ask. My most important is really being able to use the custom post title and image as the source for the autocomplete script.
    – geektripp
    Jan 21, 2017 at 20:15

1 Answer 1

2

Your question is quite complicated, but lets give it a shot!

I recently made a class that does just that that I am happy to share.

It isn't a complete response but will get you most of the way there.

What you need to know is the quirky way WP does ajax, which involves registering an action at the Wordpress ajax endpoint.

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

}

Next is the JS (will skip the 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 ) );

Cool! Now just create the class in your funcitons.php which will enqueue everything for you.

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

Done!

You could do this last step conditionally, and only include it in certain pages, posts types, etc.

To save the selected option you could create another ajax action, using the hooks like on the class above.

Your handling function could use update_user_meta with the terms

Finally, to use multiple values, you should have a look at the jQuery ui docs. You can definitely do it: https://jqueryui.com/resources/demos/autocomplete/multiple.html

I will definitely recommend smashingmag if you want good tutorials on these fiddly wordpress features: https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/

Hope that gets you started well!

12
  • Thank you so much! I want to make 100% sure I understand everything. I put the first part in my functions.php. Then I create a JS file and put the second part in it. Then, to call the form in my theme, I have to do the include with the JS file linked?
    – geektripp
    Jan 21, 2017 at 20:39
  • Yeah, its not the easiest code to explain WP ajax, but its a very nice and clean pattern. What you should do is register your ajax actions and call them through JQ. For that we enqeue a variable that has the address to the WP ajax endpoint and add it to the handling script. What that script does is that it gets everything in a single class which makes it easy to maintain Jan 21, 2017 at 20:42
  • I added a link to a smashingmag article. Its the place I go to every time I need a refresher on anything wordpress. have a look Jan 21, 2017 at 20:43
  • Ohhhh. So I don't put the first part in functions.php? I put it in it's own .php file then call that .php (not JS file) with: // 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();
    – geektripp
    Jan 21, 2017 at 20:44
  • OHH One last thing! When it says "your_theme_or_plugin_base" I don't get what goes there? Or oh is that just my website url?
    – geektripp
    Jan 21, 2017 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.