Load WordPress posts using JSON and enable search using jQuery

We’re going to load posts using JSON from a WordPress custom post type, assign the posts to a list inside a div and enable live search using jQuery.

Basic HTML page.
On page load, we’ll call a jQuery function, load_drummers_list() that loads the custom post types.




Here we’ll use the jQuery getJSON() function to retrieve the posts and populate the div with a class of drummers-list.
NOTE: The json rest api plugin needs to be installed first for this to work.

/* load drummers list into drummers.html page */
function load_drummers_list() {

	/* get CPT drummers */
	$.getJSON('wp-json/posts?type=drummer', function(data) {
		var output = '
    '; $.each(data, function(key, val) { output += '
  • '; output += '
    '; output += '
    '; output += ' '; output += '
    '; output += '
    '; output += '

    ' + val.title + '

    '; output += '

    ' + val.excerpt + '

    '; output += '
    '; output += '
    '; output += '
  • '; }); output += '
'; $('.drummers-list').html(output); }); //get JSON /* filter results based on search */ $("#filter").keyup(function(){ // Retrieve the input field text var filter = $(this).val(); // Loop through the comment list $(".drummers-list ul li").each(function(){ // If the list item does not contain the text phrase fade it out if ($(this).text().search(new RegExp(filter, "i")) < 0) { $(this).fadeOut(); // Show the list item if the phrase matches } else { $(this).show(); } }); }); }

Once the posts are loaded, the user will be able to type in a partial or full name and the results will be filtered to show the results accordingly.

Facebooktwitterlinkedinmail

by Norm Euker