Skip to content

Instantly share code, notes, and snippets.

@micjamking
Last active August 18, 2017 01:07
Show Gist options
  • Save micjamking/1458fad608dfa127760cc64d481bd16c to your computer and use it in GitHub Desktop.
Save micjamking/1458fad608dfa127760cc64d481bd16c to your computer and use it in GitHub Desktop.
Custom Search using GET params In WordPress
<?php
/**
* @fileoverview custom filter and search
*
* References
* @see http://michaelsoriano.com/how-to-create-an-advanced-search-form-for-wordpress/
* @see http://wordpress.stackexchange.com/a/50051/36130
* @see https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
*/
class namespace_search {
/**
* Taxonomy array for tax query
*/
private $item = array();
/**
* Initial tax query array
*/
private $list = array();
/**
* Form search terms
*/
public $query_terms = array();
/**
* Final tax query array (after merge)
*/
public $tax_query = '';
/**
* @constructor
*/
public function __construct($post_data) {
/**
* Create array of filter terms
* from search form $_POST data
*/
foreach($post_data as $key => $value){
if($key != 'search' && $value != ''){
/**
* Add key/values to $query_terms array
* for persisting filter values in form
*/
$this->query_terms[$key] = htmlspecialchars($value);
/** Create tax query $item from form */
$this->item['taxonomy'] = htmlspecialchars($key);
$this->item['terms'] = htmlspecialchars($value);
$this->item['field'] = 'slug';
/** Add $item to list */
$this->list[] = $this->item;
} elseif ($key == 'search' && $value != '') {
/** Persist search term */
$this->query_terms['search'] = htmlspecialchars($value);
}
}
/** Create tax_query array after list merge with relation settings */
if (count($this->list) > 0){
$this->tax_query = array_merge(array('relation' => 'AND'), $this->list);
}
}
}
<?php
/*
* Get search criterion from $_GET data
*/
$search_terms = new custom_search($_GET);
/*
* Create arguments from search query
*/
$query_terms = $search_terms->query_terms;
$tax_query = $search_terms->tax_query;
$paged = ($query_terms->paged === 1) ? $query_terms->paged : ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = [
's' => $query_terms['search'],
'post_type' => 'custom_post_type',
'posts_per_page' => '12',
'order' => 'ASC',
'paged' => $paged,
'tax_query' => $tax_query
];
/*
* Get resources via WP_Query
*/
$custom_query = new WP_Query( $args );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment