Jump to content
Larry Ullman's Book Forums

Form To Search & Filter Results From Database?


Recommended Posts

Hello,

 

First off: I would like to thank Larry for this amazing book. It isn't just very informative and thorough but also a lot of fun to learn from. Unfortunately I havn't been able to look into it as much as I want to lately.

 

 

I'm working with a php file that shows a little menu with dropdown menu's in which visitors can filter the results for price and other things before they click search and they see the results.

 

Now my internship boss wants me to add a function so visitors can fill in the product name (or a part of the product name) in a textbox which then filters out all the other products.

 

I have absolutely no idea where to start, yet my boss expects me to add this in 2 days. I really don't want to let him down either.

 

It's a huge code and I'm not sure how easy or hard it is but any help or tips would be very much appreciated.

 

 

<?php

function cps_add_query_vars( $qvars )
{
$qvars[] = 'searchquery';
return $qvars;
}


function cps_template_redirect_file()
{
global $wp_query;
if ( $wp_query->get('searchquery') )
{
if (file_exists( TEMPLATEPATH . '/custom-search.php' ))
{
include( TEMPLATEPATH . '/custom-search.php' );
exit;
}
}
}

add_filter('query_vars', 'cps_add_query_vars');

add_action('template_redirect', 'cps_template_redirect_file');

$use_ajax = get_option('cps_use_ajax');
$option = get_option('template_fields');


//$array_taxonomy = array( strtolower($options['locationtext']),strtolower($option['neighborhoodtext']), strtolower($option['featurestext']),strtolower($option['schoolareatext']));

//new code : hard coded taxonomy names to do the label fix
$array_taxonomy = array( 'location','neighborhoods', 'features','schools');

if(($option['locationhide']) == 'Yes')
{
$array_taxonomy = array_diff($array_taxonomy, array('location'));
}

if(($option['featureshide']) == 'Yes')
{
$array_taxonomy = array_diff($array_taxonomy, array('features'));
}

if(($option['neighborhoodhide']) == 'Yes')
{
$array_taxonomy = array_diff($array_taxonomy, array('neighborhoods'));
}

if(($option['schoolhide']) == 'Yes')
{
$array_taxonomy = array_diff($array_taxonomy, array('schools'));
}

$CPS_OPTIONS = array(
'meta_boxes_vars' => array($meta_boxes,$feat_boxes,$comment_boxes),
'taxonomies' => $array_taxonomy,
'per_page' => get_option('posts_per_page'),
'use_ajax' => (bool)$use_ajax,
'slider_step' => 100000,
'post_types' => array('gtre','user_listing')
);


if(isset($_GET['searchquery'])){

$search_query = $_GET['searchquery'];
$pieces = explode('/',$search_query);
$new_parts = array();
foreach($pieces as $piece){
if(!trim($piece))
 continue;
preg_match('/(?P<key>[^-]+)-(?P<val>.+)/', $piece, $matches);
if(isset($matches['key']) && isset($matches['val']))
$_GET[$matches['key']] = $matches['val'];
}

}

add_action('wp_enqueue_scripts','cps_load_scripts_and_styles');
add_action('admin_init','cps_register_options');
add_action('admin_menu','cps_settings_fields');
add_action('wp_ajax_ajax_custom_search', 'cps_ajax_search');
add_action('wp_ajax_nopriv_ajax_custom_search', 'cps_ajax_search');

/////// USE AJAX OR NOT FOR SEARCH ///////

function cps_register_options(){
register_setting('general', 'cps_use_ajax');
}

function cps_setting_field(){
?>
<label for="cps_use_ajax">On</label>
<input type="radio" name="cps_use_ajax" id="cps_use_ajax" value="1" <?php echo get_option('cps_use_ajax') == 1 ? 'checked="checked"' : '' ?> />
<label for="cps_use_ajax2">Off</label>
<input type="radio" name="cps_use_ajax" id="cps_use_ajax2" value="0" <?php echo get_option('cps_use_ajax') == 0 ? 'checked="checked"' : '' ?> />
<?php
}

function cps_settings_fields(){
add_settings_field('cps_use_ajax', 'Instant search', 'cps_setting_field', 'general' );
}

function cps_search_form()
{
global $CPS_OPTIONS;

?>
<div id="advSearchForm" class="print">
<div class="cpsAjaxLoader"><div style="text-align:center;margin-top:40px;">Zoeken naar bedrijven</div><img src="<?php bloginfo('template_url')?>/images/common/loader.gif" /><div style="text-align:center;margin-top:10px">Een ogenblik geduld</div>	
 </div>
<form action="<?php echo get_site_url(); echo '/search' ?>" method="post" id="advSearch" class="jqtransform" data-domain="<?php echo get_site_url() ?>" >
<div style="clear:both">
<?php

cps_display_taxonomy_search_form($CPS_OPTIONS['taxonomies']);


foreach($CPS_OPTIONS['meta_boxes_vars'] as $meta_boxes)
{
 cps_display_meta_box_search_form($meta_boxes);
}


$availbale_search_types = 3; //1 - both, 2 - only regular, 3 - only instant

if ($availbale_search_types == 1)
{
 ?>
 <p>Instant search:
 <label for="cps_use_ajax">On</label>
 <input type="radio" name="cps_use_ajax" id="cps_use_ajax" value="1" <?php echo (isset($_COOKIE['cps_use_ajax']) && $_COOKIE['cps_use_ajax'] == 1 ? 'checked="checked"' : '') ?> />
 <label for="cps_use_ajax2">Off</label>
 <input type="radio" name="cps_use_ajax" id="cps_use_ajax2" value="0" <?php echo (!isset($_COOKIE['cps_use_ajax']) || $_COOKIE['cps_use_ajax'] == 0 ? 'checked="checked"' : '') ?> />
 </p>
 <?php
}
elseif ($availbale_search_types == 3)
{
?>
 <input type="hidden" name="cps_use_ajax" id="cps_use_ajax" value="1" />
<?php
} else {
?>
 <input type="hidden" name="cps_use_ajax" id="cps_use_ajax" value="0" />
<?php
}
?>
</div>
<div style="clear:both"></div>
 <div class="searchsub"><input class="search-btn" type="submit" name="submit" value="Zoeken" /></div>
</form>
<div class="imgtest"> <img src="wp-includes/images/300x250.jpg" /></div>
<div style="clear:both"></div>
</div>
<?php
}

function cps_load_scripts_and_styles(){
global $CPS_OPTIONS;
wp_enqueue_script('jquery');
wp_enqueue_script('cps_jq_ui_slider',get_bloginfo('template_url').'/custom-search/js/jquery-ui-1.8.12.custom.min.js' );
wp_enqueue_script('cps_jq_hashchange',get_bloginfo('template_url').'/custom-search/js/jquery.ba-hashchange.min.js');
wp_enqueue_script('cps_jq_search',get_bloginfo('template_url').'/custom-search/js/search.js', false, '5');

}

function cps_display_meta_box_search_form($meta_boxes){

global $CPS_OPTIONS;
foreach($meta_boxes as $metaBox){

if(isset($metaBox['hide_in_search']) && $metaBox['hide_in_search'] === "Yes"){
continue;
}

switch($metaBox['type']){

case 'text':
case 'textarea':
?>

 <div class="input_text"><label><?php echo $metaBox['title'] ?></label>
 <input type="text" name="<?php echo $metaBox['name']?>" value="" /></div>

<?php
 break;

case 'range':


 $options = get_option('template_symbols');
 $Range = cps_get_range('_'.$metaBox['name']);
 if(!isset($Range->min) || !isset($Range->max)) return;
 $formatted = number_format($Range->max);

?>
	 <script type="text/javascript">
 function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;


}
</script>
<div class="drop">
<select name="price" class="dropdown">
<option value=""><?php _e('Prijs','language');?></option>
<?php
$step = $CPS_OPTIONS['slider_step'];
$start = $Range->min - $step;
$price = $start < 0 ? 0 : $start;

while( $price < $Range->max )
{
echo '<option value="' . $price .'-' . ($price+$step) . '">€' . number_format($price) . ' --- €' . number_format($price+$step) . '</option>';
$price += $step;
}
?>
</select></div>

<?php
 break;

case 'checkbox':
?>
 <div class="checkbox">
 <label><?php echo $metaBox['title'] ?></label>
 <input type="checkbox" name="<?php echo $metaBox['name']?>" value="<?php echo $metaBox['options'][1] ?>" />
 </div>
<?php
 break;

case 'radio':


 echo '<div class="radio"><label>'.$metaBox['title'].'</label><br/>';
 foreach($metaBox['options'] as $radio_value) {
 echo '<input type="radio" name="'.$metaBox['name'].'" value="'.$radio_value.'" /> '.$radio_value;
 }
 echo '</div>';

 break;

case 'dropdown':
 echo '<div class="drop">';
 echo '<select class="'.$metaBox['class'].'" name="'.$metaBox['name'].'">';
 echo '<option value="">'.$metaBox['title'].'</option>';

 foreach($metaBox['options'] as $dropdown_key => $dropdown_value) {
 echo '<option value="'.$dropdown_value.'">'.$dropdown_value.'</option>';
 }
 echo '</select></div>';

 break;
}

}
}
function cps_ajax_search($meta_boxes){
$posts = cps_search_posts();

?>
<div class="searchBreadcrumbs">

<?php '<a href="#" class="cpsBack">Home</a> »';?>
<?php cps_breadcrumbs(); ?>
</div>
<div style="clear:both"></div>
<div class="searchSort">
<?php cps_sort_by('price') ?>

</div>
<div style="clear:both"></div>

<?php $options = get_option('template_layout'); ?>


<?php if ( $options['layout_selector'] != 'left' ){ echo '<div class="grid_8 alpha common_listings left">';} else { echo '<div class="grid_8 common_listings omega right"> ';} ?>
<div class="hideOnSearch">
<ul class="search-results">

<div style="clear:both"></div>

<?php wp_reset_postdata();?>
<?php
$displayed = array();
if(!empty($posts)): foreach($posts as $post):

if(in_array($post->ID,$displayed)):
 continue;
else:
 $displayed[] = $post->ID;
 endif;
?>


<?php $field = get_option('template_fields');?><?php $fields = get_post_meta($post->ID, 'key', true);?>
<?php $symbols = get_option('template_symbols'); $fields3 = get_post_meta($post->ID, 'door', true); $fields2 = get_post_meta($post->ID, 'knob', true); ?>
<?php $blogurl = get_bloginfo('template_url'); ?>
<?php $surl = get_bloginfo('url'); ?>
<li>
<h3><a href="<?php echo $post->post_name ?>" rel="bookmark" title="Permanent Link to <?php echo $post->post_title ?>"><?php echo $post->post_title ?></a></h3>
<div class="common_left hideOnSearch">

<?php
$args = array(
'order'		 => 'ASC',
'orderby'	 => 'menu_order',
'post_type'	 => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
);


$attachments = get_posts($args);
if ($attachments) {
 foreach ($attachments as $attachment) {
 echo '<a href='.$surl.'/'.$post->post_name.'>'.wp_get_attachment_image($attachment->ID, 'thumbnail_results').'<span class="'.$fields['statustag'].'"></span></a>';
}
} ?>
</div>
<div class="common_right hideOnSearch">
<span class="results-price"><?php include(TEMPLATEPATH."/functions/var/default-box-one.php");
include(TEMPLATEPATH."/functions/var/default-box-two.php");
include(TEMPLATEPATH."/functions/var/default-box-three.php"); echo $symbols['currency']; echo $fields['price']; ?></span> | <span class="results-meta"><?php echo $fields2['bedrooms']; echo ' '.$options['bedroomstext']; ?></span> - <span class="results-meta"><?php echo $fields2['bathrooms']; echo ' '.$options['bathroomstext']; ?></span> | <span class="results-meta"><?php echo $fields['propertytype']; ?></span><br/>
<div class="excerpt_listing">
<?php
$values = get_post_meta($post->ID, 'door', true);
foreach($values as $value) {
add_filter( 'custom_filter', 'wpautop' );
echo apply_filters( 'custom_filter', rtrim(substr($value.'…',0,160)).'...<a class="more" href='.$post->post_name.'>more</a>' );
} ?>
</div>
<?php
echo nmbrpics($post->ID);
?>
</div>
<div style="clear:both"></div>
</li>
<div class="listing_divider hideOnSearch"></div>
<?php endforeach; else: ?>
<p style="padding:30px;"><?php _e('Sorry, no listings matched your criteria.','smooth');?></p>
<?php endif; ?>

<div class="pagination">
<?php cps_show_pagination() ?><br/>
</div>
</div>
</ul>
</div>
<?php
exit;
}
function cps_breadcrumbs()
{
global $CPS_OPTIONS;
$i = 0;
$link = isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'] ? '#search/' : get_site_url().'/search/';

// Taxonomies:
if( isset($CPS_OPTIONS['taxonomies']) && !empty($CPS_OPTIONS['taxonomies']) )
{
foreach($CPS_OPTIONS['taxonomies'] as $taxonomy)
{
if(isset($_GET[$taxonomy]) && trim($_GET[$taxonomy] != ''))
{
 $term = get_term_by('name', $_GET[$taxonomy], $taxonomy);

 $ins_par = '';

 $separator = $i ? '<span><strong> » </strong></span>': '';
 $link .= $i ? '/' : '';

 //$link .= $taxonomy.'-'.$_GET[$taxonomy];
 $child_link = $link . $taxonomy . '-' . $_GET[$taxonomy];
 $ready_link = $child_link . '/';

 if (isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'])
 {
 $ready_link = 'javascript:manual_hashchange(\'' . urlencode($child_link) . '/\');';
 }

 $parent_term = get_term_by('id', $term->parent, $taxonomy);

 $ins_par .= getAllParentTermsLinks($parent_term , $link, $taxonomy, $ins_par);
 /*if($parent_term)
 {
 $parent_link = $link . $taxonomy . '-' . $parent_term->name;		
 $ready_parent_link = $parent_link . '/';

 if (isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'])
 {
 $ready_parent_link = 'javascript:manual_hashchange(\'' . urlencode($parent_link) . '/\');';
 }

 $ins_par .= '<a href="' . $ready_parent_link . '">' . $parent_term->name . '</a>->';
 }
 */

 echo $separator . $ins_par .'<a href="' . $ready_link . '">' . $_GET[$taxonomy] . '</a>';
 $i++;
}
}
}

foreach($CPS_OPTIONS['meta_boxes_vars'] as $meta_boxes)
{
// Custom fields
foreach($meta_boxes as $metaBox)
{
if(isset($_GET[$metaBox['name']]) && trim($_GET[$metaBox['name']]) != '')
{
 $separator = $i ? '<span><strong> » </strong></span>': '';
 $link .= $i ? '/' : '';
 $link .= $metaBox['name'].'-'.$_GET[$metaBox['name']];
 $ready_link = $link . '/';
 if (isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'])
 {
 $ready_link = 'javascript:manual_hashchange(\'' . urlencode($link) . '/\');';
 }

 echo "$separator <a href=\"" . $ready_link . "\" class='cps_breadcrumbs'>" . $metaBox['title'] . ': ' .$_GET[$metaBox['name']]."</a>";
 $i++;
}
}
}
}


function getAllParentTermsLinks($parent_term , $link, $taxonomy, $ins_par)
{
if($parent_term)
{
$parent_link = $link . $taxonomy . '-' . $parent_term->name;		
$ready_parent_link = $parent_link . '/';

if (isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'])
{
$ready_parent_link = 'javascript:manual_hashchange(\'' . urlencode($parent_link) . '/\');';
}

$ins_par = '<a href="' . $ready_parent_link . '">' . $parent_term->name . '</a>->' . $ins_par;

$another_parent_term = get_term_by('id', $parent_term->parent, $taxonomy);

return getAllParentTermsLinks($another_parent_term , $link, $taxonomy, $ins_par);
}
else
{
return $ins_par;
}
}
function cps_get_current_link(){
global $CPS_OPTIONS;
$link = isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'] ? '#search/' : get_site_url().'/search/';
$i = 0;
// Taxonomies:
if( isset($CPS_OPTIONS['taxonomies']) && !empty($CPS_OPTIONS['taxonomies']) ){
foreach($CPS_OPTIONS['taxonomies'] as $taxonomy){
if(isset($_GET[$taxonomy]) && trim($_GET[$taxonomy] != '')){
 $link .= $i ? '/' : '';
 $link .= $taxonomy.'-'.$_GET[$taxonomy];
 $i++;
}
}
}
foreach($CPS_OPTIONS['meta_boxes_vars'] as $meta_boxes){
foreach($meta_boxes as $metaBox){
if(isset($_GET[$metaBox['name']]) && trim($_GET[$metaBox['name']]) != ''){
 $link .= $i ? '/' : '';
 $link .= $metaBox['name'].'-'.$_GET[$metaBox['name']];
 $i++;
}
}
}

$link .= $i === 0 ? '' : '/';
return $link;
}

function cps_show_pagination(){
global $RES_COUNT;
global $CPS_OPTIONS;
$links_count = ceil($RES_COUNT/$CPS_OPTIONS['per_page']);
if($links_count<2) return;
$link = cps_get_current_link();
for($i=1;$i<=$links_count;$i++){
$cur_class = '';
if(isset($_GET['page']) && $_GET['page'] == $i ){
$cur_class = 'current';
}


 if (isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax']) {
$ready_link = 'javascript:manual_hashchange("' . urlencode($link) . 'page-' . $i . '/")';
 } else {
$ready_link = $link . "page-$i/";
 }


echo "<a href='{$ready_link}' class='convertUrl $cur_class'>$i</a>";
}
}
function cps_sort_by($field){

global $CPS_OPTIONS;

$order_asc = '';
$order_desc = '';

$bOrderAsc = true;
$link = isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax'] ? '#search/' : get_site_url().'/search/';
$i = 0;
 // Taxonomies:
 if( isset($CPS_OPTIONS['taxonomies']) && !empty($CPS_OPTIONS['taxonomies']) ){
foreach($CPS_OPTIONS['taxonomies'] as $taxonomy){
if(isset($_GET[$taxonomy]) && trim($_GET[$taxonomy] != '')){
 $link .= $i ? '/' : '';
 $link .= $taxonomy.'-'.$_GET[$taxonomy];
 $i++;
}
}
 }

$cur_meta_box = array();
foreach($CPS_OPTIONS['meta_boxes_vars'] as $meta_boxes){
 if(isset($meta_boxes[$field]['name'])){
$cur_meta_box = $meta_boxes;
 }

 foreach($meta_boxes as $metaBox){
if(isset($_GET[$metaBox['name']]) && (is_array($_GET[$metaBox['name']]) || trim($_GET[$metaBox['name']]) != '')) {
$link .= $i ? '/' : '';
if (is_array($_GET[$metaBox['name']])) {
 foreach($_GET[$metaBox['name']] as $value) {
$link .= urlencode($metaBox['name'] . '[]-' . $value) . '/';
 }
 $link = substr($link, 0, -1);
} else {
 $link .= $metaBox['name'].'-'.$_GET[$metaBox['name']];
}
$i++;
}
 }
}
$link .= $i ? '/' : '';
$link .= "order-$field";

if(!isset($_GET['orderdirection']) && isset($_GET['order']) && $_GET['order'] == $cur_meta_box[$field]['name']){
 $link .= "/orderdirection-desc";
 $bOrderAsc = false;
}
if (isset($_GET['order']) && $_GET['order'] == $cur_meta_box[$field]['name']) {
$order_asc = '<img class="sort" src="' . get_bloginfo('template_directory') . '/images/common/down_arrow.png"/>';
 $order_desc = '<img class="sort" src="' . get_bloginfo('template_directory') . '/images/common/up_arrow.png"/>';
}

$link .= '/';
if (isset($_GET['cps_use_ajax']) && $_GET['cps_use_ajax']) {
 $link = 'javascript:manual_hashchange(\'' . urlencode($link) . '\');';
}
echo "<div class='sorting'>";
//if(!empty($direction)) $link .= "&orderdirection=$direction";
echo "<a class='sort_left' href=\"" . $link . "\">".($bOrderAsc ? $order_asc : $order_desc)."</a>";
echo "<a class='sort_right' href=\"" . $link . "\">Sorteer Hoog-Laag  </a>";
echo "</div>";

}
function cps_get_terms($taxonomy){

global $wpdb;

$q = "
SELECT
term.name
FROM {$wpdb->term_taxonomy} tt
INNER JOIN {$wpdb->terms} term ON term.term_id = tt.term_id
WHERE taxonomy = '$taxonomy'
";
$result = $wpdb->get_col($q);

return $result;

}


function cps_get_range($custom_field_key){
global $wpdb;

$q = "
SELECT
MAX(CAST(pm.meta_value AS SIGNED)) AS max,
MIN(CAST(pm.meta_value AS SIGNED)) AS min
FROM {$wpdb->postmeta} pm
WHERE pm.meta_key = '$custom_field_key'
";
$result = $wpdb->get_row($q);

return $result;
}

function cps_display_taxonomy_search_form($taxonomy_names){
?>

<script type="text/javascript">
jQuery(function()
{

 jQuery('#location').change(function()
 {
	 var $mainCat= jQuery('#location :selected').attr('data-value');
	 if(!$mainCat){
		 $mainCat = jQuery('#location').val();
	 }
	 // .call ajax
	 jQuery("#model").empty();
	 jQuery.ajax
	 (
	 {
		 url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
		 type:'POST',
		 data:'action=my_special_ajax_name_call&main_catid=' + $mainCat,
		 success:function(results)
		 {






			 options = jQuery(results);
if(options.length > 1){
jQuery("#model").removeAttr("disabled");
} else {
if(!jQuery("#model").is(':disabled')){
jQuery("#model").attr("disabled", "disabled");
}
}
jQuery("#model").append(results);
jQuery("#model").selectBox('destroy');
jQuery("#model").selectBox();


		 }
	 }
 );
 });
});
</script>		
<div class="drop">
<?php /*

wp_dropdown_categories_custom(array(
		 'show_count' => '1' ,
		 'selected' => '1' ,
		 'hierarchical' => '1' ,
		 'depth' => '1' ,
		 'hide_empty' => '0' ,
		 'exclude' => '1' ,
		 'class' => 'dropdown',
		 'show_option_none' => 'Stad',
		 'name' => 'location' ,
		 'taxonomy' => 'location' ,
		 'walker' => new Walker_CategoryDropdown_Custom() ,
	 ));?></div><div class="drop">
<select name="location" id="model" class="dropdown" disabled="disabled"><option value=""><?php _e('Buurt (selecteer eerst uw stad)','language');?></option></select></div>*/?>
<?php

}
function generate_dropdown_options($hTerm)
{
if(is_array($hTerm))
{
foreach($hTerm as $tChild)
{
 //echo '<option value="'.trim($tChild->name).'">'.$tChild->title.'</option>';
 generate_dropdown_options($tChild);
}
}
else
{
echo '<option value="'.trim($hTerm->name).'">'.$hTerm->title.'</option>';
}
}
$RES_COUNT = 0;

function cps_search_posts(){

global $CPS_OPTIONS;
global $wpdb;

$join = '';
$where = '';
$order = '';
$joinedMeta = array();
$i = 0;
// Custom fields
foreach($CPS_OPTIONS['meta_boxes_vars'] as $meta_boxes){
foreach($meta_boxes as $metaBox){
$mb_name = $metaBox['name'];
if(isset($_GET[$mb_name]) && trim($_GET[$mb_name]) != ''){

 $join .= " JOIN $wpdb->postmeta meta$i
	 ON meta$i.post_id = p.ID
	 AND meta$i.meta_key = '_$mb_name' ";

 if($metaBox['type'] === 'range'){
 $pieces = explode('-',$_GET[$mb_name]);
 $where .= " AND meta$i.meta_value BETWEEN $pieces[0]+0 AND $pieces[1]+0 ";
 } else {
 $where .= " AND meta$i.meta_value = '{$_GET[$mb_name]}' ";
 }

 $joinedMeta["meta$i"] = $mb_name;
 // Order:

 if(isset($_GET["order"])){
 if($_GET["order"] === $mb_name){
 $asc = isset($_GET["orderdirection"]) ? $_GET["orderdirection"] : 'ASC';
 $order .= " meta$i.meta_value $asc ";
 }
 }

// $j = 1;
// while(isset($_GET["order$j"])){
//	 if($_GET["order$j"] === $mb_name){
//	 $asc = isset($_GET["orderdirection$j"]) ? $_GET["orderdirection$j"] : 'ASC';
//	 $order .= " meta$i.meta_value $asc,";
//	 }
//	 $j++;
// }
 $i++;
} else {
 if(isset($_GET["order"])){
 if($_GET["order"] === $mb_name){
 $asc = isset($_GET["orderdirection"]) ? $_GET["orderdirection"] : 'ASC';
 $join .= " LEFT JOIN $wpdb->postmeta meta$i
		 ON meta$i.post_id = p.ID
		 AND meta$i.meta_key = '_$mb_name' ";
 $order .= " meta$i.meta_value $asc ";
 $i++;
 }
 }
}

// else {
// $j = 1;
// while(isset($_GET["order$j"])){
//	 if($_GET["order$j"] === $mb_name){
//	 $asc = isset($_GET["orderdirection$j"]) ? $_GET["orderdirection$j"] : 'ASC';
//	 $join .= " JOIN $wpdb->postmeta meta$i
//		 ON meta$i.post_id = p.ID
//		 AND meta$i.meta_key = '_$mb_name' ";
//	 $order .= " meta$i.meta_value $asc,";
//	 $i++;
//	 }
//	 $j++;
// }
// }
}
}
// Custom Taxonomies
$is_search_by_tax = false;
if( isset($CPS_OPTIONS['taxonomies']) && !empty($CPS_OPTIONS['taxonomies']) ){
foreach($CPS_OPTIONS['taxonomies'] as $taxonomy){
 if(isset($_GET[$taxonomy]) && trim($_GET[$taxonomy] != '')){
 $sAlias = preg_replace('#\W#', '_', $_GET[$taxonomy]);
 $is_search_by_tax = true;
 $where .= " AND terms_" .$sAlias . ".name = '{$_GET[$taxonomy]}' ";

 $join .= "
 JOIN $wpdb->term_relationships tr_" .$sAlias . " ON tr_" .$sAlias . ".object_id = p.ID
 JOIN $wpdb->term_taxonomy tt_" .$sAlias . " ON tr_" .$sAlias . ".term_taxonomy_id = tt_" .$sAlias . ".term_taxonomy_id
 JOIN $wpdb->terms terms_" .$sAlias . " ON terms_" .$sAlias . ".term_id = tt_" .$sAlias . ".term_id
";
 }
}
}
/*
if($is_search_by_tax){
$join .= "
 JOIN $wpdb->term_relationships tr ON tr.object_id = p.ID
 JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
 JOIN $wpdb->terms terms ON terms.term_id = tt.term_id
";
}
*/
// Pagination:
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$from = $CPS_OPTIONS['per_page']*($page_num-1);
$count = $CPS_OPTIONS['per_page'];

// Order:
$order_by = '';
if(!empty($order)){
$order_by = "ORDER BY ".rtrim($order, ',');
}

$in_posts = implode("','", $CPS_OPTIONS['post_types']);


$query = "
	 SELECT
		 p.*
	 FROM {$wpdb->base_prefix}posts p
		 $join
	 WHERE p.post_status = 'publish'
		 -- Only custom posts:
		 AND p.post_type IN ('$in_posts')
		 $where
		 $order_by
	 LIMIT $from, $count
	 ";

global $RES_COUNT;
	 global $wpdb;

	 $RES_COUNT = $wpdb->get_var("
	 SELECT
		 count(p.ID)
	 FROM {$wpdb->base_prefix}posts p
		 $join
	 WHERE p.post_status = 'publish'
		 -- Only custom posts:
		 AND p.post_type IN ('$in_posts')
		 $where
	 ");

return $wpdb->get_results($query);

}
function cps_ajax_search_results(){
echo "<div id='cps_ajax_search_results'></div>";
}
?>

 

Link to comment
Share on other sites

The easiest way to achieve what you want to do is to use the SQL LIKE keyword. I believe Larry talks about this in the book, but by using LIKE, you can search for phrases in a DB for which only a part of it matches the search term. For example, let's imagine the following simple DB:

 

Table name: titles

id  book_title
1   The Hobbit
2   The Hobo's Guide to Life
3   Hobgoblin Comic Series
4   The Lord of the Rings
5   The Man Who Hobbled to Phoenix

 

If the user were to search for the keyword "hob", you could store that search term into a PHP variable, and then search for the matching records in the DB as follows:

 

$search_term = strtoupper($_GET['search_term']); // $search_term equals "HOB" in this example.

$q = "SELECT book_title FROM titles WHERE UPPER(book_title) LIKE '%$search_term%'";

// Make the query here and do whatever you have to do with the results.

 

Note that I changed both the search term and the book_title column in the WHERE clause to uppercase in order to perform a case-insensitive search. Also note that it would be prudent to adequately cleanse the search term before using it in a query. Anyway, the above query would return all the books except "The Lord of the Rings", which is what you want.

Hopefully that makes sense.

 

As for integrating this concept into your code, I'm gonna leave that up to you.

The core of what you need to do is written above though.

Good luck, and ask follow-up questions, if need be.

Thanks.

Link to comment
Share on other sites

Thanks a lot!

 

And thank you for taking the time to help, I really appreciate it.

 

Hopefully this'll help me on my way.

I'll try it as soon as possible, when it isn't 5 in the morning where I life!

 

 

Again, thanks a lot

Link to comment
Share on other sites

 Share

×
×
  • Create New...