• I am trying to get search query string to submit custom table and count how many time these string searched

    my table column
    id(int), keyword(varchar), count(int)

    everything i made my way but problem is when submit search form its count 4 times code following bellow.

    function search_count($search) {
    
    		//table column id, keyword, count
    		// intial value 1, wordpress, 1
    		global $wpdb;
    		$table = "wp_search_count";
    		$wpdb->query("UPDATE $table SET count = count+1 WHERE keyword = '$search'");
    
    return $search;
    
    }
    add_filter( 'get_search_query', 'search_count');

    i have started count value 1 and after submit search form its should be 2 but i get 5 for count value

    Please kick me on the way …
    Thanks in Advance.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Sorry for the late reply. This issue surprises many people. You basically cannot trust any filter or action in WP to fire only once per request. They often fire more than once for reasons beyond the understanding of mere mortals. There probably are actions that actually only fire once, I don’t know what they are.

    The only action you can be sure to fire once per request is one you created and apply from code you have complete control over. One way to do this is pass requests through admin-ajax.php or admin-post.php. Your resulting action callback can update the count before passing the request on to where ever it should have gone originally. Not so simple when attempting to count built in WP processes.

    A less than elegant solution is to set a global value after the initial count increment and not do any more increments as long as the global is set.

Viewing 1 replies (of 1 total)
  • The topic ‘add_filter with get_search_query executing 4 times’ is closed to new replies.