Search: how to extend the existing search to include a custom table

I created a custom table 'products' with the following field:title,description,url.The items stored into the table are imported.

I would like to extends the wordpress search to this table. Is it possible to do this?

Topic wp-query plugin-development customization Wordpress

Category Web


Depends how you would like to do it. I am currently building a site with a custom search. I did it in a couple of steps.

  • Think about prefered url: www.example.com/search/< product_name >
  • Create a wordpress template for your custom search.
  • Add a page with the coresponding template. Note the pages id
  • Add the needed rewrite tags for it. You will use them later in your search template:

    add_action('init','custom_rewrite_tags');
    
    function custom_rewrite_tags() {
        add_rewrite_tag('%var%','([^&]+)');
    }
    
  • Now you can create your rewrite so the search is a pretty url to your liking

    add_action('admin_init','action_custom_rewrite_rules');
    function action_custom_rewrite_rules() {
        add_rewrite_rule('^search/([^&]+)/?$','index.php?page_id=<the page id>&var=$matches[1]','top'); 
    }
    

    The add rewrite rule specifies the regex to match for the url, and the coresponding query it will send to index.php. The regex captures are remmemberd in the $matches variable, starting from index 1 the first captured group. In this case whatever is www.example.com/search/< here >/ . We assign the matches to your custom rewrite tag.

  • Now in your search template you can start a function and it will have access to the rewrite tags. Example, will return your variable. If you don't like pretty url-s you can always search with a get_query:

    /*
     * Template name: Custom Search Template
     */
    $var = get_query_var('var');
    
  • And now the query

    $sql = $wpdb->prepare("SELECT * FROM myTable WHERE var = %s",
        $var);
    $results = $wpdb->get_results($sql);
    

And in results you have your results, do whatever you want with them.


By default, WordPress searches by keyword. What this means is that when passed the search query "Loren Ipsum", WordPress builds the following for the WHERE clause:

((wp_posts.post_title LIKE '%Loren%') OR
(wp_posts.post_content LIKE '%Loren%')) 
AND
((wp_posts.post_title LIKE '%Ipsum%') OR
(wp_posts.post_content LIKE '%Ipsum%'))

This answer can be helpful to you ! There is also a plugin for this : Search Everything

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.