With an ever increasing amount of content building on your Wordpress site, your users will inevitably need to search your site to find that specific helpful article from way back. To help narrow the search results, I'm going to show you how to code a plugin that allows the user to search based on category.
This tutorial includes a screencast available to Tuts+ Premium members.
The first step in our plugin's development is to decide on the feature set it'll have, plus the amount of customization available. We want our plugin to have the following features and to allow for complete user customization:
- Reconfigure search based on selected category
- Drop-down list of categories
- Ability to hide categories with no posts from list
- Ability to exclude child categories from list
- Opton to disable our inbuilt styling
- Ability to exclude specific categories from list
- Ability to use custom value in search box
- Ability to use custom value for "In all categories" selection
Creating the Skeleton for the Plugin
Before we can do anything to our plugin we first need to build the skeleton for the plugin to work in. We'll begin by creating a new folder in the Wordpress "plugins" directory (/wp-content/plugins) and title it "search-by-category" (by convention, all plugin folders should be all lowercase and use dashes in place of spaces so that when linking to files in the folder URLs are easily readable to the human eye). Create a new PHP file in the folder titled "sbc.php", this file will serve as the foundation for our entire plugin structure. Next fill, in the plugin with the required Wordpress info so that it will appear in our WP-Admin panel.
1 |
|
2 |
<?php
|
3 |
/*
|
4 |
Plugin Name: Search By Category Tutorial
|
5 |
Plugin URI: https://fire-studios.com/blog/search-by-category/
|
6 |
Description: Reconfigures search results to display results based on category of posts.
|
7 |
Version: 1.0.0
|
8 |
Author: Fire G
|
9 |
Author URI: http://fire-studios.com/blog/
|
10 |
*/
|
11 |
|
12 |
?>
|



Set-up the Options page
Now that Wordpress is recognizing our plugin, we can begin our development. First thing we need to do is setup an Options page so that we can let the user configure our plugin to their liking. How this works is a three-step process:
first we create a class for all of our configurations to operate inside.
1 |
|
2 |
if ( ! class_exists( 'SBC_Admin' ) ) { |
3 |
class SBC_Admin { |
4 |
|
5 |
}
|
6 |
}
|
Second we run a function to create the config page.
1 |
|
2 |
// prep options page insertion
|
3 |
function add_config_page() { |
4 |
if ( function_exists('add_submenu_page') ) { |
5 |
add_options_page('Search By Category Options', 'Search By Category', 10, basename(__FILE__), array('SBC_Admin','config_page')); |
6 |
}
|
7 |
}
|
Setting up the Personalization
Now that we have our config page up, we can start adding in our config options for us to apply later in the plugin. To display our config page we're going to have to create a new function called "config_page()" which we'll fill with the rest of our admin section code. First we'll go ahead and write the HTML for all our sections.
1 |
|
2 |
<div class="wrap"> |
3 |
<hr /><h2>Seach By Category Options</h2> |
4 |
<form action="" method="post" id="sbc-config"> |
5 |
<table class="form-table"> |
6 |
<?php if (function_exists('wp_nonce_field')) { wp_nonce_field('sbc-updatesettings'); } ?>
|
7 |
<tr>
|
8 |
<th scope="row" valign="top"><label for="search-text">Display text in the search box:</label></th> |
9 |
<td><input type="text" name="search-text" id="search-text" class="regular-text" value="<?php echo $search_text; ?>"/></td> |
10 |
</tr>
|
11 |
<tr>
|
12 |
<th scope="row" valign="top"><label for="focus">Display text in drop-down selection:</label></th> |
13 |
<td><input type="text" name="focus" id="focus" class="regular-text" value="<?php echo $focus; ?>"/></td> |
14 |
</tr>
|
15 |
<tr>
|
16 |
<th scope="row" valign="top"><label for="hide-empty">Hide categories with no posts?</label></th> |
17 |
<td><input type="checkbox" name="hide-empty" id="hide-empty" value="1" <?php if ($hide_empty == '1') echo 'checked="checked"'; ?> /></td> |
18 |
</tr>
|
19 |
<tr>
|
20 |
<th scope="row" valign="top"><label for="exclude-child">Exclude Child categories from list?</label></th> |
21 |
<td><input type="checkbox" name="exclude-child" id="exclude-child" value="1" <?php if ($exclude_child == '1') echo 'checked="checked"'; ?> /></td> |
22 |
</tr>
|
23 |
<tr>
|
24 |
<th scope="row" valign="top"><label for="sbc-style">Use the SBC Form styling?</label></th> |
25 |
<td><input type="checkbox" name="sbc-style" id="sbc-style" value="1" <?php if ($sbc_style == '1') echo 'checked="checked"'; ?> /> <em>* Styling doesn't display correctly in IE7 and earlier *</em></td> |
26 |
</tr>
|
27 |
<tr>
|
28 |
<th scope="row" valign="top"><label for="focus">Categories to exclude:</label></th> |
29 |
<td><ul><?php wp_category_checklist(0,0,$raw_excluded_cats); ?></ul></td> |
30 |
</tr>
|
31 |
</table>
|
32 |
<br/>
|
33 |
<span class="submit" style="border: 0;"><input type="submit" name="submit" value="Save Settings" /></span> |
34 |
</form>
|
35 |
</div>
|
You'll notice that we're already using PHP to reference the variables: $search_text, $focus, $hide_empty, $exclude_child, $sbc_style, and $raw_excluded_cats (in the function "wp_category_checklist"). We'll create and expand these variables in the next step.



Full Screencast

Adding our Options to the Database
Now that the admin page is up and running we can start using it to add options to the Database. To do this, we're simply just going to create a variable before the "if ( ! class_exists( 'SBC_Admin' ) ) {" and then use the Wordpress function "add_option('entry-title','value')" to insert it into the wp_options table of the DB. Here's the list of the variables we'll be using in our plugin:
- $focus - The default text the viewer sees in the selection drop-down
- $hide_empty - true or false, removes categories with 0 posts from the drop-down
- $excluded_cats - a comma separated array of the excluded categories
- $raw_excluded_cats - array of the excluded categories
- $search_text - The default text in the search box of the form
- $exclude_child - true or false, removes child categories from the drop-down
- $sbc_style - true or false, use the custom SBC stylesheet
1 |
|
2 |
// Some Defaults
|
3 |
$focus = 'In All Categories'; |
4 |
$hide_empty = '1'; // 1 means true |
5 |
$excluded_cats = array(); |
6 |
$search_text = 'Search For...'; |
7 |
$exclude_child = '0'; // 0 means false |
8 |
$raw_excluded_cats = array(); |
9 |
$sbc_style = '1'; |
10 |
|
11 |
// Put our defaults in the "wp-options" table
|
12 |
add_option("sbc-focus", $focus); |
13 |
add_option("sbc-hide-empty", $hide_empty); |
14 |
add_option("sbc-excluded-cats", $excluded_cats); |
15 |
add_option("sbc-search-text", $search_text); |
16 |
add_option("sbc-selected-excluded", $raw_excluded_cats); |
17 |
add_option("sbc-exclude-child", $exclude_child); |
18 |
add_option("sbc-style", $sbc_style); |
Now that we have our defaults set and added to the database, we can use Wordpress' "get_option('entry-title')" function in our config_page function so that our values are reflected inside the forms.
1 |
|
2 |
function config_page(){ |
3 |
$focus = get_option("sbc-focus"); |
4 |
$hide_empty = get_option("sbc-hide-empty"); |
5 |
$search_text = get_option("sbc-search-text"); |
6 |
$excluded_cats = get_option("sbc-excluded-cats"); |
7 |
$exclude_child = get_option("sbc-exclude-child"); |
8 |
$raw_excluded_cats = get_option("sbc-selected-excluded"); // For Checklist |
9 |
$sbc_style = get_option("sbc-style"); |



Now that our Options page is using the data from the database, let's setup the update process. To begin with we're going to start a new if statement checking if our submit button is set. Next we'll compare our wpnonce to verify that the user visited the page before trying to update the options. Then we'll run another if statement to check and make sure the current is allowed to change the settings by running the WP function "current_user_can('manage_options')", if they can't, then we'll kill the script.
1 |
|
2 |
if ( isset($_POST['submit']) ) { |
3 |
$nonce = $_REQUEST['_wpnonce']; |
4 |
if (! wp_verify_nonce($nonce, 'sbc-updatesettings') ) die('Security check failed'); |
5 |
if (!current_user_can('manage_options')) die(__('You cannot edit the search-by-category options.')); |
6 |
check_admin_referer('sbc-updatesettings'); |
7 |
}
|
Now we'll update the variables we defined earlier with the input value from the form. Since we're using checkboxes for the excluded categories list, the best way to get the return we want from it is to declare another if statement and check that "post_category" (the id given to the list by the WP function) is set. If it is present, then we're going to take its raw form and place back into the "$raw_excluded_cats" variable from earlier so that the checkboxes will remain checked. We're also going to use those same return values to create a "pretty" comma separated array for later use by adding one extra value to the start of the array (This is a fix for a glitch later on in another function) and then implode the array.
1 |
|
2 |
// Get our new option values
|
3 |
$focus = $_POST['focus']; |
4 |
$hide_empty = $_POST['hide-empty']; |
5 |
$search_text = $_POST['search-text']; |
6 |
$exclude_child = $_POST['exclude-child']; |
7 |
$sbc_style = $_POST['sbc-style']; |
8 |
|
9 |
if(isset($_POST['post_category'])){ |
10 |
$raw_excluded_cats = $_POST['post_category']; |
11 |
|
12 |
// Fix our excluded category return values
|
13 |
$fix = $raw_excluded_cats; |
14 |
array_unshift($fix, "1"); |
15 |
$excluded_cats = implode(',',$fix); |
16 |
}
|
Because of the very nature of checkboxes, they only have a return value if they're checked, so we need to write a catch for when they're not checked. To do this we're going to use a simple if statement that checks to see if our variables are empty (since there's no return value from the form to fill it with), if it is empty, we're going set the value to "0" (false).
1 |
|
2 |
// Make sure "$hide_empty" & "$exclude_child" are set right
|
3 |
if (empty($hide_empty)) $hide_empty = '0'; // 0 means false |
4 |
if (empty($exclude_child)) $exclude_child = '0'; // 0 means false |
5 |
if (empty($sbc_style)) $sbc_style = '0'; // 0 means false |
Now our last step is to update the database with our new values using the Wordpress function "update_option('entry-title','new-value')". We're also going to wrap the values we're inserting into the DB with the function mysql_real_escape_string() to help prevent any SQL injection.
1 |
|
2 |
// Update the DB with the new option values
|
3 |
update_option("sbc-focus", mysql_real_escape_string($focus)); |
4 |
update_option("sbc-hide-empty", mysql_real_escape_string($hide_empty)); |
5 |
update_option("sbc-selected-excluded", mysql_real_escape_string($raw_excluded_cats)); |
6 |
update_option("sbc-excluded-cats", mysql_real_escape_string($excluded_cats)); |
7 |
update_option("sbc-search-text", mysql_real_escape_string($search_text)); |
8 |
update_option("sbc-exclude-child", mysql_real_escape_string($exclude_child)); |
9 |
update_option("sbc-style", mysql_real_escape_string($sbc_style)); |
Our code So far:
1 |
|
2 |
<?php
|
3 |
/*
|
4 |
Plugin Name: Search By Category Tutorial
|
5 |
Plugin URI: http://fire-studios.com/blog/search-by-category/
|
6 |
Description: Reconfigures search results to display results based on category of posts.
|
7 |
Version: 1.0.0
|
8 |
Author: Fire G
|
9 |
Author URI: http://fire-studios.com/blog/
|
10 |
*/
|
11 |
|
12 |
// Some Defaults
|
13 |
$focus = 'In All Categories'; |
14 |
$hide_empty = '1'; // 1 means true |
15 |
$excluded_cats = array(); |
16 |
$search_text = 'Search For...'; |
17 |
$exclude_child = '0'; // 0 means false |
18 |
$raw_excluded_cats = array(); |
19 |
$sbc_style = '1'; |
20 |
|
21 |
// Put our defaults in the "wp-options" table
|
22 |
add_option("sbc-focus", $focus); |
23 |
add_option("sbc-hide-empty", $hide_empty); |
24 |
add_option("sbc-excluded-cats", $excluded_cats); |
25 |
add_option("sbc-search-text", $search_text); |
26 |
add_option("sbc-selected-excluded", $raw_excluded_cats); |
27 |
add_option("sbc-exclude-child", $exclude_child); |
28 |
add_option("sbc-style", $sbc_style); |
29 |
|
30 |
if ( ! class_exists( 'SBC_Admin' ) ) { |
31 |
|
32 |
class SBC_Admin { |
33 |
|
34 |
// prep options page insertion
|
35 |
function add_config_page() { |
36 |
if ( function_exists('add_submenu_page') ) { |
37 |
add_options_page('Search By Category Options', 'Search By Category', 10, basename(__FILE__), array('SBC_Admin','config_page')); |
38 |
}
|
39 |
}
|
40 |
|
41 |
function config_page() { |
42 |
if ( isset($_POST['submit']) ) { |
43 |
$nonce = $_REQUEST['_wpnonce']; |
44 |
if (! wp_verify_nonce($nonce, 'sbc-updatesettings') ) die('Security check failed'); |
45 |
if (!current_user_can('manage_options')) die(__('You cannot edit the search-by-category options.')); |
46 |
check_admin_referer('sbc-updatesettings'); |
47 |
|
48 |
// Get our new option values
|
49 |
$focus = $_POST['focus']; |
50 |
$hide_empty = $_POST['hide-empty']; |
51 |
$search_text = $_POST['search-text']; |
52 |
$exclude_child = $_POST['exclude-child']; |
53 |
$sbc_style = $_POST['sbc-style']; |
54 |
|
55 |
if(isset($_POST['post_category'])){ |
56 |
$raw_excluded_cats = $_POST['post_category']; |
57 |
|
58 |
// Fix our excluded category return values
|
59 |
$fix = $raw_excluded_cats; |
60 |
array_unshift($fix, "1"); |
61 |
$excluded_cats = implode(',',$fix); |
62 |
}
|
63 |
|
64 |
// Make sure "$hide_empty" & "$exclude_child" are set right
|
65 |
if (empty($hide_empty)) $hide_empty = '0'; // 0 means false |
66 |
if (empty($exclude_child)) $exclude_child = '0'; // 0 means false |
67 |
if (empty($sbc_style)) $sbc_style = '0'; // 0 means false |
68 |
|
69 |
// Update the DB with the new option values
|
70 |
update_option("sbc-focus", mysql_real_escape_string($focus)); |
71 |
update_option("sbc-hide-empty", mysql_real_escape_string($hide_empty)); |
72 |
update_option("sbc-selected-excluded", mysql_real_escape_string($raw_excluded_cats)); |
73 |
update_option("sbc-excluded-cats", mysql_real_escape_string($excluded_cats)); |
74 |
update_option("sbc-search-text", mysql_real_escape_string($search_text)); |
75 |
update_option("sbc-exclude-child", mysql_real_escape_string($exclude_child)); |
76 |
update_option("sbc-style", mysql_real_escape_string($sbc_style)); |
77 |
}
|
78 |
|
79 |
$focus = get_option("sbc-focus"); |
80 |
$hide_empty = get_option("sbc-hide-empty"); |
81 |
$search_text = get_option("sbc-search-text"); |
82 |
$excluded_cats = get_option("sbc-excluded-cats"); |
83 |
$exclude_child = get_option("sbc-exclude-child"); |
84 |
$raw_excluded_cats = get_option("sbc-selected-excluded"); // For Admin Checklist |
85 |
$sbc_style = get_option("sbc-style"); |
86 |
|
87 |
?>
|
88 |
<div class="wrap"> |
89 |
<hr /><h2>Seach By Category Options</h2> |
90 |
<form action="" method="post" id="sbc-config"> |
91 |
<table class="form-table"> |
92 |
<?php if (function_exists('wp_nonce_field')) { wp_nonce_field('sbc-updatesettings'); } ?> |
93 |
<tr>
|
94 |
<th scope="row" valign="top"><label for="search-text">Display text in the search box:</label></th> |
95 |
<td><input type="text" name="search-text" id="search-text" class="regular-text" value="<?php echo $search_text; ?>"/></td> |
96 |
</tr>
|
97 |
<tr>
|
98 |
<th scope="row" valign="top"><label for="focus">Display text in drop-down selection:</label></th> |
99 |
<td><input type="text" name="focus" id="focus" class="regular-text" value="<?php echo $focus; ?>"/></td> |
100 |
</tr>
|
101 |
<tr>
|
102 |
<th scope="row" valign="top"><label for="hide-empty">Hide categories with no posts?</label></th> |
103 |
<td><input type="checkbox" name="hide-empty" id="hide-empty" value="1" <?php if ($hide_empty == '1') echo 'checked="checked"'; ?> /></td> |
104 |
</tr>
|
105 |
<tr>
|
106 |
<th scope="row" valign="top"><label for="exclude-child">Exclude Child categories from list?</label></th> |
107 |
<td><input type="checkbox" name="exclude-child" id="exclude-child" value="1" <?php if ($exclude_child == '1') echo 'checked="checked"'; ?> /></td> |
108 |
</tr>
|
109 |
<tr>
|
110 |
<th scope="row" valign="top"><label for="sbc-style">Use the SBC Form styling?</label></th> |
111 |
<td><input type="checkbox" name="sbc-style" id="sbc-style" value="1" <?php if ($sbc_style == '1') echo 'checked="checked"'; ?> /> <em>* Styling doesn't display correctly in IE7 and earlier *</em></td> |
112 |
</tr>
|
113 |
<tr>
|
114 |
<th scope="row" valign="top"><label for="focus">Categories to exclude:</label></th> |
115 |
<td><ul><?php wp_category_checklist(0,0,$raw_excluded_cats); ?></ul></td> |
116 |
</tr>
|
117 |
</table>
|
118 |
<br/>
|
119 |
<span class="submit" style="border: 0;"><input type="submit" name="submit" value="Save Settings" /></span> |
120 |
</form>
|
121 |
</div>
|
122 |
<?php
|
123 |
} // Config page |
124 |
} // Class |
125 |
} // If class exists |
126 |
|
127 |
// insert into admin panel
|
128 |
add_action('admin_menu', array('SBC_Admin','add_config_page')); |
129 |
|
130 |
?>
|
Creating the Form
Now that we've got our back end all set and ready to deploy, it's time to start writing the front-end form that all the visitors will see and use. So that our user can place our form anywhere on his site that he wants, we're going to encase our form within a new function titled "sbc()" placed just outside of our class declaration. The first bytes of code we need to add are declaring a global $wp_query and $post so we can have access to those functions if we desire later on, but for our purposes we won't need them. Next step is to re-obtain our variables values from the database.
1 |
|
2 |
// Base function
|
3 |
function sbc() { |
4 |
|
5 |
$focus = get_option("sbc-focus"); |
6 |
$hide_empty = get_option("sbc-hide-empty"); |
7 |
$excluded_cats = get_option("sbc-excluded-cats"); |
8 |
$search_text = get_option("sbc-search-text"); |
9 |
$exclude_child = get_option("sbc-exclude-child"); |
10 |
|
11 |
}
|
Once we've done that, we can create another variable called "$list" with its value being the WP function wp_dropdown_categories($settings) (read more on this function here). That variable "$settings" is where most of our customization is being applied.
1 |
|
2 |
$settings = array('show_option_all' => $focus, |
3 |
'show_option_none' => '', |
4 |
'orderby' => 'name', |
5 |
'order' => 'ASC', |
6 |
'show_last_update' => 0, |
7 |
'show_count' => 0, |
8 |
'hide_empty' => $hide_empty, |
9 |
'child_of' => 0, |
10 |
'exclude' => "'".$excluded_cats."'", |
11 |
'echo' => 0, |
12 |
'selected' => 0, |
13 |
'hierarchical' => 1, |
14 |
'name' => 'cat', |
15 |
'class' => 'postform', |
16 |
'depth' => $exclude_child); |
17 |
$list = wp_dropdown_categories($settings); |
Now that the form's dropdown is configured, we can create another variable, "$form" which will hold our form HTML via a hypertext preprocessor. then we'll echo our new $form variable.
1 |
|
2 |
$blog_url = get_bloginfo("url"); |
3 |
|
4 |
$form = <<< EOH |
5 |
<div id="sbc"> |
6 |
<form method="get" id="sbc-search" action="{$blog_url}"> |
7 |
<input type="text" value="{$search_text}" name="s" id="s" onblur="if (this.value == '') {this.value = '{$search_text}';}" onfocus="if (this.value == '{$search_text}') {this.value = '';}" /> |
8 |
{$list} |
9 |
<input type="submit" id="sbc-submit" value="Search" /> |
10 |
</form> |
11 |
</div> |
12 |
EOH; |
13 |
|
14 |
echo $form; |
Adding in the Custom Styling
Earlier we gave the user an option of using our custom styling for the form. If they left this option enabled in the settings menu, we need to add our stylesheet to the header. Easiest way to do this is to create a new if statement checking for our variable "$sbc_style" to be true (in our code: 1). Inside that check, we'll add in a new function "style_insert()" that echoes out the URL to our stylesheet. Also in the if (but outside the function), we'll write in a new action for "wp_head" to add in our function "style_insert()".
1 |
|
2 |
if($sbc_style == '1'){ |
3 |
// Add our styling
|
4 |
function style_insert() { |
5 |
$current_path = get_option('siteurl') . '/wp-content/plugins/' . basename(dirname(__FILE__)); |
6 |
?>
|
7 |
<link href="<?php echo $current_path; ?>/sbc-style.css" type="text/css" rel="stylesheet" /> |
8 |
<?php
|
9 |
}
|
10 |
|
11 |
// insert custom stylesheet
|
12 |
add_action('wp_head','style_insert'); |
13 |
}
|
As for our styling, create a new file called sbc-style.css fill it with:
1 |
|
2 |
form#sbc-search {clear: both;} |
3 |
form#sbc-search * {margin: 0px;} |
4 |
|
5 |
form#sbc-search input#s {background: #f5f5f5; |
6 |
border: 1px solid #bbbbbb; |
7 |
padding: 4px 10px; |
8 |
width: 80%; |
9 |
margin-bottom: 10px;} |
10 |
|
11 |
form#sbc-search select#cat {display: block; |
12 |
background: #fbfbfb; |
13 |
height: 30px; |
14 |
width: 63%; |
15 |
border: 1px solid #bbbbbb; |
16 |
float: left; |
17 |
padding: 4px 20px; |
18 |
border-right: none; |
19 |
-khtml-appearance: none; /* fix default safai styling */ |
20 |
border-radius: 15px 0px 0px 15px; |
21 |
-webkit-border-bottom-left-radius: 15px; |
22 |
-webkit-border-top-left-radius: 15px; |
23 |
-moz-border-radius: 15px 0px 0px 15px;} |
24 |
|
25 |
form#sbc-search select#cat option {padding: 2px 4px;} |
26 |
|
27 |
form#sbc-search input#sbc-submit {display: block; |
28 |
height: 30px; |
29 |
width: 37%; |
30 |
border: 1px solid #bbbbbb; f |
31 |
loat: right; |
32 |
border-radius: 0px 15px 15px 0px; |
33 |
-webkit-border-bottom-right-radius: 15px; |
34 |
-webkit-border-top-right-radius: 15px; |
35 |
-moz-border-radius: 0px 15px 15px 0px;} |



In Safari you'll notice that the standard downward triangle is missing from our dropdown box, this is because we used -khtml-appearance: none on the dropdown to stop safari from forcing it's "snow" theme onto it. a way to fix this is to use an HTML character to simulate the triangle, and there happens to be one very similar called "∇ Nabla". We'll use a combination of spaces, non-breaking-spaces, and this nabla in the dropdown settings to fix this issue.
1 |
|
2 |
$settings = array('show_option_all' => $focus.' ∇', |
3 |
'show_option_none' => '', |
4 |
'orderby' => 'name', |
5 |
'order' => 'ASC', |
6 |
'show_last_update' => 0, |
7 |
'show_count' => 0, |
8 |
'hide_empty' => $hide_empty, |
9 |
'child_of' => 0, |
10 |
'exclude' => "'".$excluded_cats."'", |
11 |
'echo' => 0, |
12 |
'selected' => 0, |
13 |
'hierarchical' => 1, |
14 |
'name' => 'cat', |
15 |
'class' => 'postform', |
16 |
'depth' => $exclude_child); |



Returning the Search Results
Once we got our form up and going, we can finally start getting the search results we're looking to give our visitors. To start us off, we'll create a new function called return_only_selected_category(), in which we'll create a new if statement checking that our search submit button is set. Inside that we need to create a new global $wp_query. Next we'll take the selected category return and place it into a variable called $desired_cat. In case the user selected the option for all categories, we need to run a check for the value "*" and reset it to "".
1 |
|
2 |
// Get results only from selected category
|
3 |
function return_only_selected_category() { |
4 |
if (isset($_POST['sbc-submit'])){ |
5 |
global $wp_query; |
6 |
|
7 |
$desired_cat = $_POST['cat']; |
8 |
if ($desired_cat == '*') $desired_cat = ''; |
9 |
}
|
10 |
}
|
Now we need to create another variable, $excluded, whose value is the WP function get_categories(). We're going to be adding 2 arguments to this function. First is "hide_empty=false" so that all categories are brought into the list, and second is "exclude={$desired_cat}" so that any categories that the category the user wants to view posts from is removed from the list.
1 |
|
2 |
$excluded = get_categories('hide_empty=false&exclude={$desired_cat}'); |
Once that variable is set, we can finally make it so that only posts from the selected category will appear in the results. For this effect, we're going to alter the Query Vars so that Wordpress removes posts from every category we list (and it just so happens we have a variable full of categories to exclude).
1 |
|
2 |
$wp_query->query_vars['cat'] = '-' . $excluded; |
By adding a dash in front of the list of categories, we're telling Wordpress to remove those from the query. A very effective method for us. Now the only thing left to do is add a new WP filter for "pre_get_posts" adding in our new function.
1 |
|
2 |
// Highjack the search
|
3 |
add_filter('pre_get_posts', 'return_only_selected_category'); |
How to Insert our Form
1 |
|
2 |
<?php if(function_exists('sbc')){ |
3 |
sbc(); |
4 |
} else { ?> |
5 |
...your standard form code here... |
6 |
<?php } ?> |
Our Finished Code
1 |
|
2 |
<?php
|
3 |
/*
|
4 |
Plugin Name: Search By Category
|
5 |
Plugin URI: http://fire-studios.com/blog/search-by-category/
|
6 |
Description: Reconfigures search results to display results based on category of posts.
|
7 |
Version: 1.1
|
8 |
Author: Fire G
|
9 |
Author URI: http://fire-studios.com/blog/
|
10 |
*/
|
11 |
|
12 |
/*
|
13 |
Change log
|
14 |
|
15 |
1.1
|
16 |
- Added security fixes
|
17 |
- Removed some excess code
|
18 |
|
19 |
1.0.0
|
20 |
- Default text
|
21 |
- Custom styling
|
22 |
|
23 |
Beta 3
|
24 |
- Search Text
|
25 |
- Exclude Child categories
|
26 |
- search box auto empties and refills if nothing entered
|
27 |
|
28 |
Beta 2
|
29 |
- First complete working version
|
30 |
- Hide Empty
|
31 |
- Focus
|
32 |
- Exclude Categories
|
33 |
|
34 |
Beta 1
|
35 |
- First working version
|
36 |
- Category exclustion from drop-down list isn't functional
|
37 |
|
38 |
Alpha 1
|
39 |
- All functions are present but independent
|
40 |
|
41 |
*/
|
42 |
|
43 |
// Some Defaults
|
44 |
$focus = 'In All Categories'; |
45 |
$hide_empty = '1'; // 1 means true |
46 |
$excluded_cats = array(); |
47 |
$search_text = 'Search For...'; |
48 |
$exclude_child = '0'; // 0 means false |
49 |
$raw_excluded_cats = array(); |
50 |
$sbc_style = '1'; |
51 |
|
52 |
// Put our defaults in the "wp-options" table
|
53 |
add_option("sbc-focus", $focus); |
54 |
add_option("sbc-hide-empty", $hide_empty); |
55 |
add_option("sbc-excluded-cats", $excluded_cats); |
56 |
add_option("sbc-search-text", $search_text); |
57 |
add_option("sbc-selected-excluded", $raw_excluded_cats); |
58 |
add_option("sbc-exclude-child", $exclude_child); |
59 |
add_option("sbc-style", $sbc_style); |
60 |
|
61 |
// Start the plugin
|
62 |
if ( ! class_exists( 'SBC_Admin' ) ) { |
63 |
|
64 |
class SBC_Admin { |
65 |
|
66 |
// prep options page insertion
|
67 |
function add_config_page() { |
68 |
if ( function_exists('add_submenu_page') ) { |
69 |
add_options_page('Search By Category Options', 'Search By Category', 10, basename(__FILE__), array('SBC_Admin','config_page')); |
70 |
}
|
71 |
}
|
72 |
|
73 |
// Options/Settings page in WP-Admin
|
74 |
function config_page() { |
75 |
if ( isset($_POST['submit']) ) { |
76 |
$nonce = $_REQUEST['_wpnonce']; |
77 |
if (! wp_verify_nonce($nonce, 'sbc-updatesettings') ) die('Security check failed'); |
78 |
if (!current_user_can('manage_options')) die(__('You cannot edit the search-by-category options.')); |
79 |
check_admin_referer('sbc-updatesettings'); |
80 |
|
81 |
// Get our new option values
|
82 |
$focus = $_POST['focus']; |
83 |
$hide_empty = $_POST['hide-empty']; |
84 |
$search_text = $_POST['search-text']; |
85 |
$exclude_child = $_POST['exclude-child']; |
86 |
$sbc_style = $_POST['sbc-style']; |
87 |
|
88 |
if(isset($_POST['post_category'])){ |
89 |
$raw_excluded_cats = $_POST['post_category']; |
90 |
|
91 |
// Fix our excluded category return values
|
92 |
$fix = $raw_excluded_cats; |
93 |
array_unshift($fix, "1"); |
94 |
$excluded_cats = implode(',',$fix); |
95 |
}
|
96 |
|
97 |
// Make sure "$hide_empty" & "$exclude_child" are set right
|
98 |
if (empty($hide_empty)) $hide_empty = '0'; // 0 means false |
99 |
if (empty($exclude_child)) $exclude_child = '0'; // 0 means false |
100 |
if (empty($sbc_style)) $sbc_style = '0'; // 0 means false |
101 |
|
102 |
// Update the DB with the new option values
|
103 |
update_option("sbc-focus", mysql_real_escape_string($focus)); |
104 |
update_option("sbc-hide-empty", mysql_real_escape_string($hide_empty)); |
105 |
update_option("sbc-selected-excluded", mysql_real_escape_string($raw_excluded_cats)); |
106 |
update_option("sbc-excluded-cats", mysql_real_escape_string($excluded_cats)); |
107 |
update_option("sbc-search-text", mysql_real_escape_string($search_text)); |
108 |
update_option("sbc-exclude-child", mysql_real_escape_string($exclude_child)); |
109 |
update_option("sbc-style", mysql_real_escape_string($sbc_style)); |
110 |
}
|
111 |
|
112 |
$focus = get_option("sbc-focus"); |
113 |
$hide_empty = get_option("sbc-hide-empty"); |
114 |
$search_text = get_option("sbc-search-text"); |
115 |
$excluded_cats = get_option("sbc-excluded-cats"); |
116 |
$exclude_child = get_option("sbc-exclude-child"); |
117 |
$raw_excluded_cats = get_option("sbc-selected-excluded"); // For Admin Checklist |
118 |
$sbc_style = get_option("sbc-style"); |
119 |
|
120 |
?>
|
121 |
<div class="wrap"> |
122 |
<hr /><h2>Seach By Category Options</h2> |
123 |
<form action="" method="post" id="sbc-config"> |
124 |
<table class="form-table"> |
125 |
<?php if (function_exists('wp_nonce_field')) { wp_nonce_field('sbc-updatesettings'); } ?> |
126 |
<tr>
|
127 |
<th scope="row" valign="top"><label for="search-text">Display text in the search box:</label></th> |
128 |
<td><input type="text" name="search-text" id="search-text" class="regular-text" value="<?php echo $search_text; ?>"/></td> |
129 |
</tr>
|
130 |
<tr>
|
131 |
<th scope="row" valign="top"><label for="focus">Display text in drop-down selection:</label></th> |
132 |
<td><input type="text" name="focus" id="focus" class="regular-text" value="<?php echo $focus; ?>"/></td> |
133 |
</tr>
|
134 |
<tr>
|
135 |
<th scope="row" valign="top"><label for="hide-empty">Hide categories with no posts?</label></th> |
136 |
<td><input type="checkbox" name="hide-empty" id="hide-empty" value="1" <?php if ($hide_empty == '1') echo 'checked="checked"'; ?> /></td> |
137 |
</tr>
|
138 |
<tr>
|
139 |
<th scope="row" valign="top"><label for="exclude-child">Exclude Child categories from list?</label></th> |
140 |
<td><input type="checkbox" name="exclude-child" id="exclude-child" value="1" <?php if ($exclude_child == '1') echo 'checked="checked"'; ?> /></td> |
141 |
</tr>
|
142 |
<tr>
|
143 |
<th scope="row" valign="top"><label for="sbc-style">Use the SBC Form styling?</label></th> |
144 |
<td><input type="checkbox" name="sbc-style" id="sbc-style" value="1" <?php if ($sbc_style == '1') echo 'checked="checked"'; ?> /> <em>* Styling doesn't display correctly in IE7 and earlier *</em></td> |
145 |
</tr>
|
146 |
<tr>
|
147 |
<th scope="row" valign="top"><label for="focus">Categories to exclude:</label></th> |
148 |
<td><ul><?php wp_category_checklist(0,0,$raw_excluded_cats); ?></ul></td> |
149 |
</tr>
|
150 |
</table>
|
151 |
<br/>
|
152 |
<span class="submit" style="border: 0;"><input type="submit" name="submit" value="Save Settings" /></span> |
153 |
</form>
|
154 |
</div>
|
155 |
<?php } |
156 |
}
|
157 |
}
|
158 |
|
159 |
// Base function
|
160 |
function sbc() { |
161 |
$focus = get_option("sbc-focus"); |
162 |
$hide_empty = get_option("sbc-hide-empty"); |
163 |
$excluded_cats = get_option("sbc-excluded-cats"); |
164 |
$search_text = get_option("sbc-search-text"); |
165 |
$exclude_child = get_option("sbc-exclude-child"); |
166 |
|
167 |
$settings = array('show_option_all' => $focus.' ∇', |
168 |
'show_option_none' => '', |
169 |
'orderby' => 'name', |
170 |
'order' => 'ASC', |
171 |
'show_last_update' => 0, |
172 |
'show_count' => 0, |
173 |
'hide_empty' => $hide_empty, |
174 |
'child_of' => 0, |
175 |
'exclude' => "'".$excluded_cats."'", |
176 |
'echo' => 0, |
177 |
'selected' => 0, |
178 |
'hierarchical' => 1, |
179 |
'name' => 'cat', |
180 |
'class' => 'postform', |
181 |
'depth' => $exclude_child); |
182 |
$list = wp_dropdown_categories($settings); |
183 |
|
184 |
$blog_url = get_bloginfo("url"); |
185 |
|
186 |
$form = <<< EOH |
187 |
<div id="sbc"> |
188 |
<form method="get" id="sbc-search" action="{$blog_url}"> |
189 |
<input type="text" value="{$search_text}" name="s" id="s" onblur="if (this.value == '') {this.value = '{$search_text}';}" onfocus="if (this.value == '{$search_text}') {this.value = '';}" /> |
190 |
{$list} |
191 |
<input type="submit" id="sbc-submit" value="Search" /> |
192 |
</form> |
193 |
</div> |
194 |
EOH; |
195 |
|
196 |
echo $form; |
197 |
}
|
198 |
|
199 |
// Get results only from selected category
|
200 |
function return_only_selected_category() { |
201 |
if (isset($_POST['sbc-submit'])){ |
202 |
global $wp_query; |
203 |
|
204 |
$desired_cat = $_POST['cat']; |
205 |
if ($desired_cat == '*') $desired_cat = ''; |
206 |
|
207 |
$excluded = get_categories('hide_empty=false&exclude={$desired_cat}'); |
208 |
|
209 |
$wp_query->query_vars['cat'] = '-' . $excluded; |
210 |
}
|
211 |
}
|
212 |
|
213 |
if($sbc_style == '1'){ |
214 |
// Add our styling
|
215 |
function style_insert() { |
216 |
$current_path = get_option('siteurl').'/wp-content/plugins/'.basename(dirname(__FILE__)); |
217 |
|
218 |
echo '<link href="'.$current_path.'/sbc-style.css" type="text/css" rel="stylesheet" />'; |
219 |
}
|
220 |
|
221 |
// insert custom stylesheet
|
222 |
add_action('wp_head','style_insert'); |
223 |
}
|
224 |
|
225 |
// Highjack the search
|
226 |
add_filter('pre_get_posts', 'return_only_selected_category'); |
227 |
|
228 |
// insert into admin panel
|
229 |
add_action('admin_menu', array('SBC_Admin','add_config_page')); |
230 |
?>
|