Integrate admin plugin into template. Very interesant (live search + autocomplete with wp rest api, in vanilla js)

I need a live search with wp rest api with autocomplete, in vanilla js. I found this plugin makes exacly what I needed. (I dont need this code as a plugin, its not a problem, but if it helps to make it easier, if anyone knows how to do this code works without it beign a plugin, let me know.)

TUTORIAL: https://sabrinazeidan.com/wp-rest-api-search-with-autocomplete-with-vanilla-js/

Github: https://github.com/sabrina-zeidan/sz-rest-api-tut

In this case, the plugin creates a page into the tools section but it doesnt gives me support to integrate it into the template , and I dont know how execute it into the template by myself. The code is shown above:

<?php
/**
 * Plugin Name: SZ WP REST API Tutorial
 * Description: It's an example of WP REST API usage for search with autocomplete with vanilla JS
 * Plugin URI:  
 * Author:      Sabrina Zeidan
 * Author URI:  https://sabrinazeidan.com
 * License:     GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 *
 */

defined( 'ABSPATH' ) or die();

class SZ_WP_REST_API_Tut { 
    function __construct() {        
        add_action( 'admin_menu', array( $this, 'admin_menu' ) ); //Add an item to the Tools menu       
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), array( $this, 'plugin_actions_links' ) ); //Add a link on Plugins page
        
        add_action( 'rest_api_init', array( $this, 'rest_api_init') ); // Initialize the REST API routes.       
    } 
 
    public function admin_menu() {
           $hook = add_management_page( 'SZ WP REST API', 'SZ WP REST API', 'manage_options', 'sz-search', array( $this, 'admin_page_content' )); //Add a page to the Tools menu
           add_action( "load-$hook", array( $this, 'admin_page_load' ) );//hook to load stuff on that page
    }
    function plugin_actions_links( array $actions ) {
            return array_merge( array(
            'sz-search'    => sprintf('<a href="%s">%s</a>', esc_url( admin_url( 'tools.php?page=sz-search' ) ),esc_html__( 'See it', '' ))), $actions );
    }
    function admin_page_load() {
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); // Load needed JavaScript and CSS     
    }
    
    function enqueue_scripts() {
            wp_enqueue_style( 'awesomplete-css', plugin_dir_url( __FILE__ ) . 'awesomplete/awesomplete.css'); //Awesomplete widget
            wp_enqueue_script('awesomplete-js', plugin_dir_url( __FILE__ ) . 'awesomplete/awesomplete.js'); //Awesomplete widget
            wp_enqueue_script('sz-search', plugin_dir_url( __FILE__ ) . 'search.js', array('awesomplete-js')); //Our Awesomplete settings are here
            wp_localize_script('sz-search', 'szsearch', array(
                'search_url' => home_url( '/wp-json/sz-search/search?term=' ), // URL to access REST API endpoint
                'nonce' => wp_create_nonce('wp_rest') ) //For authorization
            );  
    }
    
    function rest_api_init() { 
        register_rest_route( 'sz-search', '/search', array( 
            'methods'  => 'GET',
            'callback' => array( $this, 'sz_rest_api_search'), //exactly how we search
            'permission_callback' => function( WP_REST_Request $request ) { return current_user_can( 'manage_options' ); } //Restrict endpoint to  internal calls 
        ) );
    }
    
    function sz_rest_api_search( WP_REST_Request $request ) {
        $search_term = $request->get_param( 'term' );//Our input from the field
        if ( empty( $search_term ) ) {
            return;
        }   
            //The way we're gonna search
            $args = array(
                'post_type' => 'post',
                'post_status' => 'publish',
                'posts_per_page'   => 3,
                'fields'   => 'ids',
                's'             => $search_term,
                'no_found_rows' => true,  
                'update_post_meta_cache' => false,
                'update_post_term_cache' => false,
                );
            $the_query = new WP_Query( $args );                             
            $this_blog_found_posts = $the_query->posts;
                $temp = array();
                foreach( $this_blog_found_posts as $key => $post_id) { 
                    $temp = array(
                        'ID' => $post_id,
                        'permalink' => get_permalink($post_id),
                        'label' => get_the_title($post_id),
                        );
                    $posts[] = $temp;                                           
                }   
        
            if (!empty($posts)) return $posts;
    }   
    
    function admin_page_content() {
        echo '<div class="wrap">';
        echo '<h1>' . esc_html_x( 'SZ WP REST API Search with autocomplete with Vanilla JavaScript', 'admin page title', 'sz-wp-rest-api-search' ) . '</h1>';       
        echo '<p>This is a search field intended to demostrate a result of WP REST API. Does it work? :)</br>';
        echo '<p><input type="text" size="80" id="sz-search-field" name="sz-search-field" value="" placeholder="Start typing the title of the post...">';//Our search field
        echo '<br><input type="hidden" size="80" id="sz_result_id" name="sz_result_id" value="">';//Hidden field to pass post ID
        echo '<br><input type="hidden" size="80" id="sz_result_permalink" name="sz_result_permalink" value="">';//Hidden field to pass post permalink
        echo '</div>';
    }
}
new SZ_WP_REST_API_Tut(); //Let's do it!
?>

What Ive tried is to create the object, and then call the function that shows the input field.

<?php
    $search = new SZ_WP_REST_API_Tut();
    $search->admin_page_content();
?>

This shows the input field, but it doesnt make the live search works. I would try more solutions by myself but in this case I dont know what more can I do, I’m stucked.

$299 Affordable Web Design WordPress

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Integrate admin plugin into template. Very interesant (live search + autocomplete with wp rest api, in vanilla js)

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.