WordPress: Filter Shortcode

Did you ever needed a input field in wordpress to filter a list, table or other items? You can create a shortcode to create such fields on various sites.

The Javascript Function

For this filter we will use the javascript function I have already explained in another post.

/**************************************************************************************
 * Filters items in the selected DOM nodes.
 * The items which sould be filtered based on their HTML content have to be marked with
 * the class "filterable".
 *@param context the Jquery selector for the element containing the items which should be filtered.
 *@param searchFieldID the ID of the field containing the search string.
 *@param itemSelector the JQuery selector for the object which should be filtered.
 *************************************************************************************/
function filterItems(context, searchFieldID, itemSelector){

	var filterContext = $(context);
	var input = $(searchFieldID);

	filter = input.val().toUpperCase();
	
	filterContext.find(itemSelector).each(function( index ) {
		  
		  if ($(this).html().toUpperCase().indexOf(filter) > -1) {
			  $(this).css("display", "");
		  } else {
			  $(this).css("display", "none");
			}
	});

}

1. Add Javascript

Copy the above code into a custom javascript file. In your functions.php, add the javascript to wordpress:

wp_enqueue_script( 'custom.js', get_template_directory_uri() . '/js/custom.js', array('custom'), NULL, true );

2. Create Shortcode

Add the following code to your functions.php. This will add the shortcode which can be used in the editor.

/**************************************************************************************
 * Shorcode function for creating a filter field
 #
 * @param context the Jquery selector for the element containing the items which should be filtered.
 * @param filterid the ID of the field containing the search string.
 * @param filterby the JQuery selector for the object which should be filtered.
 *************************************************************************************/
function custom_filter($atts) { 
	$attributes = shortcode_atts( array(
		'filterid' => 'filterField', // id of the field used for filtering
		'context' => '#filterContext', //ID of the DOM Element containing the items to be filtered
		'filterby' => '.filterable', //ID of the DOM Element containing the items to be filtered
	), $atts );
	
	$html = '<input id="'. $attributes['filterid'] .'" class="form-control w-100 mb-2" onkeyup="filterItems(\''.  $attributes['context']  .'\', \'#'. $attributes['filterid'] .'\', \''. $attributes['filterby'] .'\')" placeholder="Filter...">';
			 
	return $html;
}
add_shortcode( 'filter', 'custom_filter' );

3. Using the shortcode

You are ready to start using the shortcode.
I use it on this blog in combination of some other shortcodes I have created.
For example I combine it with a tag list(find the example here).

  • By default, the filter will search for items marked with the class “filterable”.
  • The taglist shortcode creates a <div>-element with id=”taglist” containing items which are already marked with the class “filterable”.
[filter context="#taglist"]
[taglist]

And above will result in the following:


abradvantagesafassetsafbrushesaffinityaffinity photoaffinityphotoalertalienampereanalyzerantAPC-Sarticifialartificialawkbarbecuebarbequebashbathroombbqbitmapblueprintblueprintsboltbootstrapbrightnessbrushbrushesburnburningcameracamera rawcigarettecirclecircuitcolorfulcolorizedcombustcombustioncomparecomputer scienceconfigurationcontrastconvertcreatecrematecrumbcrumbscurrentcurvescustomercutecybercyberspacedangerdatabasedecorationdesigndesignerdetailsdetonatedetonationdevelopmentdigitaldirtdirtydivdocumentationdogdotsdownloaddramadramaticdrawingdrawingsdrinkdropdropsDSLRdustdustydynamiceffecteffectselectricelectricalelectricityelectroelectronicsenergyenhancementsepsexceptionexplodeexplosionexplosivefacefantasyfictionfieldfilterfilthfilthyfirefixflameflamesflashflourfluidfontawesomeformulafreefreewareftpfunctionfunnyfuturefuturisticgallerygalvanicgamegaminggasturbinegaugegawkgbrgenericgifgimpgirlgithubgradientgradient mapgraphsgreengrillinggrungeguitarhalloweenhandhanddrawnharheadershellhellfirehihi-techi-techhighhigh resolutionhitechhothtaccesshttp archiveillustrationimageimagesimpactincenerateinfographicinfographicsinfraredinkscapeinstallinstructionsissuesITitemsjavajavamonamourjavascriptjpegjpgjquerylandscapelayer styleslevelslightlightinglightninglightningboltlightningslinelineslinuxlistloadlocalhostlovelymapmaskmathematicsmavenmechanicalmechanicsmethodmigratemindmusicnaturalnatureohmopensourceoptimizeoutsideoverlayoverlayspageparodyparticleparticlespdfperformancephotophotographyphotomanipulationphotoshootphotoshoppicturepicturespierluigiplantpngpointspoolpositivepostpowderpowerpregnancypregnantpreparationprocessproductpsdpseudopunkpythonpython-furadialrainrainbowrealisticredred treesrefineremoveresresizingresolutionsandscalescaryscattersci-fisciencescifiscorchscriptingscyteservershapeshapes bitmapshellshockshockingshootshortshortcodesignssizeskeletonskullsmart objectsmokesmoothsolid colorspacesparksparklessparklingsparksspecialspecklesspermspiritualsplashsplashessplashingstampstarssteamsteampunkstepstepsstorystrokestrokesstrutsstylessuckssvgswimmingsystemtabletable of contentstaglisttechtechnologytemplatethemethunderthunderboltthunderstormtifftitlestoctorchtracingtravellingturbinetutorialvectorvectorizationvernettoversusvideovoltvoltagewaterwebweblogicwetwhite treeswirewomanwordpresswp-configyogayoutube

Share:


developmentfilterjavascriptshortcodethemewordpress

Leave a Reply

Your email address will not be published.