Autocomplete post titles in meta box in post edit

I’ve been trying to solve the following problem – I need to get title and ID of other posts while editing post. This data would be used to generate shortcode suggestion to include in post. All of this is part of a plugin. I added metabox like this:

function addPostHelperMetaBox()
{
add_meta_box(
‘post-helper’,
__(‘Post helper’),
‘postMetaBox’,
‘post’
);
}
add_action(‘add_meta_boxes’, ‘addPostHelperMetaBox’);

function postMetaBox()
{
?>
<input id=”search-input”>
<input id=”post-search-result”>
<?php
}

Here is how the scripts are added:

add_action( ‘admin_init’, ‘setup_my_scripts’ );

function setup_my_scripts()
{
add_action( ‘wp_enqueue_scripts’, ‘my_scripts’ );
}

function my_scripts()
{
global $wpdb;

$results_array = $wpdb->get_results(“SELECT ID,post_title FROM {$wpdb->posts}
WHERE post_type = ‘post’
AND post_status = ‘publish'”);

wp_register_script(‘jquery-ui-autocomplete’, plugin_dir_path(__FILE__) . ‘js/jquery-ui.min.js’, [‘jquery’], ‘1.12.1’, false);

wp_enqueue_script(‘jquery-ui-autocomplete’);

wp_enqueue_script( ‘post-ajax-search’, plugin_dir_path(__FILE__) .’js/ajax-search.js’, [ ‘jquery-ui-autocomplete’, ‘jquery’ ], ‘1.0.0’, false);

wp_localize_script(‘post-ajax-search’, ‘posts’, [‘autocomplete’ => json_encode($results_array)]);
}

And the js:
jQuery(document).ready(function($) {

var autocomplete_terms = JSON.parse( posts.autocomplete );

$(‘#search-input’).click(function() {
alert(“your clicked”);
});

$(‘#search-input’).autocomplete({
source: autocomplete_terms,
minLength: 2
});

});

I tried various implementation but none of them seem to work. Now I have a bunch of code that is mixed up, not working and I don’t know where the problem is.
This are some of the solutions that I tried:

jQuery autocomplete in WordPress

Autocomplete or suggest from post titles inside plugin

Adding jquery ui autocomplete to the wordpress search

I don’t even get click function to work.

Read more here:: Autocomplete post titles in meta box in post edit

Leave a Reply

Your email address will not be published. Required fields are marked *