Word Press Hacking

Well, as per usual, I wanted more out of my WordPress and hence got it. This time, it was searching. I don’t know when the basic searching was added to WordPress, but I really like MySQL’s FULLTEXT matching abilities, so I went to implement them on my site. NOTE: this is not a plugin and does indeed cause you to modify core files. preform at own risk.

I started by copying the searchform.php out of the default template and adding it into my current template’s folder. That is for ease of typing. I then opened my template’s header file (you might put this in sidebar.php also) and added in for it to include searchform.php by writing (note i added a div so i could edit its appearance in css):

I verified that my edits worked and updated my css to display that div as I wanted it. The search should currently work, although poorly. Next, I modified my database. You need to execute the following query on the database that holds your wordpress tables. (You can execute it from the sql input in phpMyAdmin if you have that set up. Note that this assumes the default prefix of wp_ that you should change as appropriate): ALTER TABLE `wp_posts` ADD FULLTEXT `realsearch` (`post_title`,`post_content`) Next was time to modify the actual search function of WordPress. This is stored in the wp-includes/classes.php and is in the get_posts() function of WP_Query. You need to do the following:

  1. locate line 416 and cut it (it comes after the comment about search pattern and reads $search = ' AND (';)
  2. add the following after line 424***:
    if(strlen($q['s'])>3){
    $search .= " AND MATCH(`post_content`,`post_title`) AGAINST('".mysql_escape_string($q['s'])."' IN BOOLEAN MODE) ";
    } else {
  3. paste the line below this.
  4. add a closing brace after the closing brace of the next else (should end on line 448, add another on line 449 so you can read it)

You may want to alter the lines around 580 to have it order by the match…against clause also, but you have to be aware that wordpress will add post_ to the beginning of the $q[‘orderby’] clause by default. i decided to override the $q[‘orderby’] with ‘score’ when i was matching fulltext and then editted line 585 (4 for me since i removed part) to add the direct section if needed. the place where $post_ is added was changed also to only occur if it was not matching fulltext.

i tested and made all this on my new child. Her name is Sin. She is a Mac. I am somewhat ashamed to admit how nice it is to work with. More on that later though. To look at my finished file, browse over to http://cardamar.quad341.com/classes.phps. Enjoy.

*** = for some reason, I cannot use IN BOOLEAN MODE on this server but can on my testing server. Just remove it for it to work again. If anyone can explain that, i’d be appreciative.