Skip to content

Instantly share code, notes, and snippets.

@DrizzlyOwl
Created December 2, 2015 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrizzlyOwl/0ecccbea76b3e586f4ff to your computer and use it in GitHub Desktop.
Save DrizzlyOwl/0ecccbea76b3e586f4ff to your computer and use it in GitHub Desktop.
Search query
<?php
// ---- //
function do_search(){
global $wpdb;
if(isset($wpdb)):
// assign all variables from our get data
$filter_year = isset($_GET['pub_year']) ? $_GET['pub_year'] : '';
$filter_month = isset($_GET['pub_month']) ? $_GET['pub_month'] : '';
$filter_keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
// clear existing queries
$wpdb->flush();
$select = "SELECT * FROM wp_posts";
$where =
" WHERE post_type = 'publication'
AND post_status = 'publish'
AND post_excerpt LIKE '%$filter_keyword%' ";
$where .=
" OR post_type = 'publication'
AND post_status = 'publish'
AND post_title LIKE '%$filter_keyword%'";
$order_by = " ORDER BY post_date DESC";
$sql = $select . $where . $order_by;
if ( !defined('WP_DEBUG') ):
$wpdb->show_errors();
endif;
$results["query"] = array(
"sql" => $sql,
"year" => $filter_year,
"month" => $filter_month,
"keyword" => $filter_keyword
);
$results["results"] = $wpdb->get_results($sql);
$results["found_posts"] = $wpdb->num_rows;
return $results;
else:
throw new Exception("Error contacting wpdb", 1);
exit;
endif;
}
<?php
$results = do_search();
$query = $results["query"];
$posts = $results["results"];
$found_posts = $results["found_posts"];
//$sql = $query["sql"];
$filter_year = $query["year"];
$filter_month = $query["month"];
$filter_keyword = $query["keyword"];
// set taxonomy term type
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
// Set your response when there are no results found
function return_no_results(){
echo '<p class="push--top">Sorry no results for this search.</p>';
}
if( $found_posts > 0 ): ?>
<?php foreach ($posts as $post_object) : $post = get_post($post_object->ID); setup_postdata($post);?>
<?php
$published_month = get_the_time(get_the_date('m'));
$published_year = get_the_time(get_the_date('Y'));
if (($filter_year == '' OR $filter_year == $published_year) AND ($filter_month == '' OR $filter_month == $published_month) AND (has_term($filter_type, 'publication_type', $post->ID))) :
$match = 1;
?>
<!-- content goes here -->
<?php endif; ?>
<?php endforeach; wp_reset_postdata(); ?>
<?php if (!$match): ?>
<?php return_no_results(); ?>
<?php endif ?>
<?php else: ?>
<?php return_no_results(); ?>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment