Can someone review my code , I need to know better solutions or any bug.
Okey ! , I made a PHP file to get search results by parameters and search by title , content and tag
PHP’s head look like:
include('../../../../wp-config.php');
header('Content-type:text/html;charset=utf-8');
$keyword = $_GET['k'];
That I will bring search results by jQuery after.
My main search function to show result from database:
function search($keyword,$mark){
while($data=mysql_fetch_array($keyword)){
if($data['post_status']=='publish'){
echo '<li>#'.$data['ID'].' '.htmlentities($data['post_title']).' ('.$mark.')</li>';
}
}
}
Search by title function : Full keyword (ex : “jack daniels”)
$sql_full_keyword = "SELECT * from wp_posts WHERE post_title LIKE '$keyword%'";
$search_full_keyword = mysql_query($sql_full_keyword) or die(mysql_error());
search($search_full_keyword,"Full keyword(s) = '$keyword'");
So i split keyword for next steps like :
$keywords_split = explode(" ",$keyword);
Search by title function : multi keywords (ex : jack + daniels)
for($i=0;$i<count($keywords_split);$i++){
$sql_split_keyword = "SELECT * from wp_posts WHERE post_title LIKE '$keywords_split[$i]%'";
$search_split_keyword = mysql_query($sql_split_keyword) or die(mysql_error());
search($search_split_keyword,"Split keyword = '$keywords_split[$i]'");
}
Search by content function : (same above, but search by content)
for($i=0;$i<count($keywords_split);$i++){
$sql_split_keyword = "SELECT * from wp_posts WHERE post_content LIKE '$keywords_split[$i]%'";
$search_split_keyword = mysql_query($sql_split_keyword) or die(mysql_error());
search($search_split_keyword,"Split keyword = '$keywords_split[$i]' (Content)");
}
Than close mysql
mysql_close();
Search by tag function : (using normal wordpress query)
$tags = str_replace(" ","-",$keyword).",".str_replace(" ",",",$keyword);
query_posts(array('post_type'=>array('one','two','three') ,'tag' => $tags,'posts_per_page'=>-1));
while (have_posts()):the_post();
echo '<li>#'.get_the_ID().' '.get_the_title().'</li>';
endwhile;
Everything work now and I need someone to review my code, tell me better things or tong …
Full code here : http://snipt.org/zpz0
Thanks
Search in WordPress is complicated matter because:
Building search from scratch is involved (I know because I did exactly that for a while for clients) and you should totally look for search plugins or other compromise (like search as service) first.
To briefly enumerate specific issues with your code:
query_posts()
should not be used, see When should you use WP_Query vs query_posts() vs get_posts()?