Knowing what your users are searching for can be extremely useful and important. In this members-only tutorial we’re going to look at how to create a simple search logging plugin that will record every search query performed on your site. We will be using the WP_Logging class that I released a week or two ago as the main backbone to the plugin.

The WP_Logging class can be downloaded from Github

The complete code written in the tutorial is shown below. Note! I have also built a more complete version, including admin page, that is available for download at the bottom of the page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!--?php
/*
Plugin Name: Search Logging
Plugin URI: https://pippinsplugins.com/search-logging
Description: Logs all search queries and demonstrates how to use WP_Logging
Version: 1.0
Author: Pippin Williamson
Author URI: https://pippinsplugins.com
Contributors: mordauk 
*/
 
 
class PW_Search_Logging {
 
	function __construct() {
 
		// load extra files
		$this--->includes();
 
		// load our actions
		$this-&gt;actions();
 
		// apply our filters
		$this-&gt;filters();
 
 
	}
 
	private function includes() {
 
		if( ! class_exists( 'WP_Logging' ) )
			require_once( dirname( __FILE__ ) . '/WP_Logging.php' );
 
	}
 
 
	private function actions() {
 
		add_action( 'template_redirect', array( $this, 'log_search' ) );
	}
 
 
	private function filters() {
 
		add_filter( 'wp_log_types', array( $this, 'log_types' ) );
 
	}
 
 
	public function log_types( $types ) {
 
		$types[] = 'search';
 
		return $types;
 
	}
 
 
	public function log_search() {
 
		if( ! is_search() )
			return; // only log a query if we are on a search
 
		$log_title    = __( 'Search: ' ) . get_search_query();
		$log_message = json_encode( $_SERVER );
 
		WP_Logging::add( $log_title, $log_message, 0, 'search' );
 
	}
 
}
 
// load our class
$GLOBALS['pw_search_logging'] = new PW_Search_Logging();

[download id=”51″ format=”1″]

  1. corsonr

    The class is really helpful and is very easy to implement, thanks!

    • Pippin

      Great to hear! This tutorial was inspired by your plugin 😉

  2. Yael Reinhardt-Matsliah

    Pippin,

    I just wanted to tell you much I am enjoying your tutorials! As a designer and not really a coder, I’ve been wanting to dive deeper into coding and understanding how things actually work in WP, etc, and your tutorials have actually made me excited to dig deeper into the code world! Thanks so much — Yael

    • Pippin

      Glad to hear it!

Comments are closed.