0

I have been trying to use the "suggest" feature inside a plugin in wordpress. I have a custom type and when I create a new post I use a text input meta box to write inside the titles of other posts of the same type. I want to use the suggest feature so that it autocompletes the titles of the post a user is writing. I have been searching a lot and finally I added this inside my plugin:

add_action('wp_enqueue_scripts', 'se_wp_enqueue_scripts');
function se_wp_enqueue_scripts() {
    wp_enqueue_script('suggest');
}

add_action('wp_footer', 'se_wp_head');
function se_wp_head() {
?>
<script type="text/javascript">
var se_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';

jQuery(document).ready(function() {
    jQuery('#requisitos_curso_disc').suggest(se_ajax_url + '?action=se_lookup', {minchars:2});
});
</script>

<?php
}

add_action('wp_ajax_se_lookup', 'se_lookup');
add_action('wp_ajax_nopriv_se_lookup', 'se_lookup');

function se_lookup() {

    $search = $wpdb->esc_like($_REQUEST['q']);

    $loop = new WP_Query( 's=' . $search );

    while( $loop->have_posts() ) {
            $loop->the_post();
            echo get_the_title()."\n";
    }

    wp_reset_query();
    wp_die();
}

But it doesn't work. Help please?

2
  • Do you have any error message ? (php logs or javascript console). Also, did you register your sugest script somewhere else ?
    – Sladix
    Commented Nov 18, 2015 at 13:19
  • I havent registered suggest anywhere else. No errors in console :S Commented Nov 18, 2015 at 14:12

1 Answer 1

3

In order to properly enqueue a script you must use the wp_enqueue_script like this :

wp_enqueue_script( 'suggest', get_template_directory_uri() . '/js/path/to/suggest.js', array('jquery'), '1.0.0', true );

The second parameter is the path to your JavaScript file, the third parameter is the dependencies the script relies on (since suggest is a jquery plugin, it must be loaded after jquery).

If you are using this, I'm afraid your call to the suggest plugin is done wrong. You whould fetch the terms first.

I personnally recommend you to use jquery ui autocomplete. I implemented it this way :

function my_autocomplete()
{
  $query = new WP_Query(array('post_type'=>'page','posts_per_page'=>-1));
  $tab = array();
  foreach ($query->posts as $p) {
    $tab[] =array('value'=>$p->post_title,'url'=>get_the_permalink($p));
  }
  die(json_encode($tab));
}
add_action( 'wp_ajax_nopriv_my_autocomplete', 'my_autocomplete' );
add_action( 'wp_ajax_my_autocomplete', 'my_autocomplete' );

the above code is in my functions.php (since you are doing a plugin, it can be in your plugin). You can change post_type to whatever you want to query. You also have to enqueue jquery ui, which is done this way :

wp_register_script('jqui', 'https://code.jquery.com/ui/1.11.4/jquery-ui.min.js', array('jquery')); // Conditional script(s)
wp_enqueue_script('jqui'); // Enqueue it!

Then in my footer.php I have

<script type="text/javascript">
    var ajaxUrl = "/wp-admin/admin-ajax.php";
</script>

In order to define the ajax url needed by the autocompletion. Finally, the actual javascript autocomplete code (assuming your input has the class search-input):

    var data = {
        action : 'my_autocomplete'
    }

    $.post(ajaxUrl,data,function(res){
    $( ".search-input" ).autocomplete({
      minLength: 0,
      source: function(request, response) {
                var results = $.ui.autocomplete.filter(res, request.term);

                response(results.slice(0, 10));
            }
      })
      .autocomplete( "instance" )._renderItem = function( ul, item ) {
          return $( "<li>" )
            .append( "<a href='"+item.url+"'>" + item.value +"</a>" )
            .appendTo( ul );
      };
    },'JSON');

So when it loads, it fetches all your page title and provide your .search-input autocomplete with the pages url. Settings here limits the autocomplete results to 10 in order to avoid gigantic lists.

This solution might not be adapted if there is a large amount of pages.

Hope it will help you.

2
  • This is very complete, thankyou. But one question, you tell me to place this in functions.php, but I am trying to do this directly in the plugin, it is not associated to any template. Where should I place them then? Commented Nov 18, 2015 at 14:52
  • Oh ok my bad, you can place it in your plugin ! Tell me if you manage to get this working !
    – Sladix
    Commented Nov 18, 2015 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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