Search form results.
-
Hi All,
I’ve been learning how to build a search form. Below is the code I am using. The trouble is the results are not specific enough. For instance if I type in ‘web design’ the results are all over the place it seems to be picking up any post or page with the words web design within the content it’s also bizarrely picking up variables from my custom fields that I created with Advance Custom Fields. I would greatly appreciate any pointers and advice. Cheers.
<?php /* Template Name: Search Page */ ?> <?php get_header(); ?> <h1>Search Results</h1> <div class="container"> <?php $term = $_GET['s']; $expTerm = explode(" ",$term); $search = "("; foreach($expTerm as $ek=>$ev) { if($ek == 0) { $search .= " post_title LIKE '%".$ev."%' "; } else { $search .= " OR post_title LIKE '%".$ev."%'"; } } $search .= ")"; $query = $wpdb->get_results(" SELECT * FROM ".$wpdb->prefix."posts WHERE post_status='publish' AND $search "); /* build a position array for the term */ $position = 101; $rate = []; for($i=0; $i<=100; $i++) { $position = $position - 1; // first run will equal 100 $rate[$i] = $position; } /* build the array based on type and position */ /* loop through the query */ $newArray = []; foreach($query as $k=>$v) { $title = $v->post_title; /* loop though each term */ $calculate = 0; foreach($expTerm as $tk=>$tv) { if(strpos(strtolower($title), strtolower($tv)) !== false) { $calculate = $calculate + strlen($tv); $pos = strpos(strtolower($title), strtolower($tv)); $calculate = $calculate + $rate[$pos]; } // end of if statement } // end of the for each term $newKey = $calculate.'.'.$v->ID; $newArray[$newKey] = $v; //print $newKey.'<br />'; } // end of for each result or query /* sort in reverse DESC */ krsort($newArray); foreach($newArray as $qk=>$qv) { $link = get_permalink($qv->ID); ?> <h3><a href="<?php echo $link; ?>"><?php echo $qv->post_title; ?></a></h3> <p><?php echo wp_trim_words($qv->post_content,40,'... <a href="'.$link.'">Continue Reading</a>'); ?></p> <?php } ?> </div> <?php get_footer(); ?>
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Search form results.’ is closed to new replies.