() translation by (you can also view the original English article)
Da auf Ihrer Wordpress-Website immer mehr Inhalte erstellt werden, müssen Ihre Benutzer unweigerlich Ihre Website durchsuchen, um diesen speziellen hilfreichen Artikel von früher zu finden. Um die Suchergebnisse einzugrenzen, zeige ich Ihnen, wie Sie ein Plugin codieren, mit dem der Benutzer anhand der Kategorie suchen kann.
Dieses Tutorial enthält einen Screencast, der Tuts+ Premium-Mitgliedern zur Verfügung steht.
Der erste Schritt in der Entwicklung unseres Plugins besteht darin, den Funktionsumfang sowie den Umfang der verfügbaren Anpassungen festzulegen. Wir möchten, dass unser Plugin die folgenden Funktionen bietet und eine vollständige Benutzeranpassung ermöglicht:
- Konfigurieren Sie die Suche basierend auf der ausgewählten Kategorie neu
- Dropdown-Liste der Kategorien
- Möglichkeit, Kategorien ohne Beiträge aus der Liste auszublenden
- Möglichkeit, untergeordnete Kategorien von der Liste auszuschließen
- Opton, um unser eingebautes Styling zu deaktivieren
- Möglichkeit, bestimmte Kategorien von der Liste auszuschließen
- Möglichkeit, benutzerdefinierte Werte im Suchfeld zu verwenden
- Möglichkeit, benutzerdefinierte Werte für die Auswahl "In allen Kategorien" zu verwenden
Erstellen des Skeletts für das Plugin
Bevor wir etwas mit unserem Plugin tun können, müssen wir zuerst das Skelett erstellen, damit das Plugin funktioniert. Wir beginnen mit der Erstellung eines neuen Ordners im Wordpress-Verzeichnis "plugins" (/wp-content/plugins) und nennen ihn "search-by-category" (gemäß Konvention sollten alle Plugin-Ordner in Kleinbuchstaben geschrieben sein und Bindestriche verwenden von Leerzeichen, damit beim Verknüpfen mit Dateien im Ordner URLs für das menschliche Auge leicht lesbar sind). Erstellen Sie eine neue PHP-Datei im Ordner "sbc.php". Diese Datei dient als Grundlage für unsere gesamte Plugin-Struktur. Füllen Sie anschließend das Plugin mit den erforderlichen Wordpress-Informationen aus, damit sie in unserem WP-Admin-Bereich angezeigt werden.
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 |
?>
|



Richten Sie die Seite Optionen ein
Nachdem Wordpress unser Plugin erkannt hat, können wir mit unserer Entwicklung beginnen. Als erstes müssen wir eine Optionsseite einrichten, damit der Benutzer unser Plugin nach seinen Wünschen konfigurieren kann. Wie dies funktioniert, ist ein dreistufiger Prozess:
Zuerst erstellen wir eine Klasse, in der alle unsere Konfigurationen ausgeführt werden können.
1 |
|
2 |
if ( ! class_exists( 'SBC_Admin' ) ) { |
3 |
class SBC_Admin { |
4 |
|
5 |
}
|
6 |
}
|
Zweitens führen wir eine Funktion aus, um die Konfigurationsseite zu erstellen.
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 |
}
|
Einrichten der Personalisierung
Nachdem wir unsere Konfigurationsseite geöffnet haben, können wir unsere Konfigurationsoptionen hinzufügen, damit wir sie später im Plugin anwenden können. Um unsere Konfigurationsseite anzuzeigen, müssen wir eine neue Funktion namens "config_page()" erstellen, die wir mit dem Rest unseres Admin-Abschnittscodes füllen. Zuerst schreiben wir den HTML-Code für alle unsere Abschnitte.
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>
|
Sie werden feststellen, dass wir bereits PHP verwenden, um auf die Variablen zu verweisen: $search_text, $focus, $hide_empty, $exclude_child, $sbc_style und $raw_excluded_cats (in der Funktion "wp_category_checklist"). Wir werden diese Variablen im nächsten Schritt erstellen und erweitern.



Vollbild

Hinzufügen unserer Optionen zur Datenbank
Jetzt, da die Administrationsseite aktiv ist, können wir damit Optionen zur Datenbank hinzufügen. Dazu erstellen wir einfach eine Variable vor dem "if (! class_exists( 'SBC_Admin' )) {" und verwenden dann die Wordpress-Funktion "add_option('entry-title', 'value')" to Fügen Sie es in die Tabelle wp_options der Datenbank ein. Hier ist die Liste der Variablen, die wir in unserem Plugin verwenden werden:
- $focus - Der Standardtext, den der Betrachter in der Auswahl-Dropdown-Liste sieht
- $hide_empty - true oder false, entfernt Kategorien mit 0 Posts aus der Dropdown-Liste
- $excluded_cats - ein durch Kommas getrenntes Array der ausgeschlossenen Kategorien
- $raw_excluded_cats - Array der ausgeschlossenen Kategorien
- $search_text - Der Standardtext im Suchfeld des Formulars
- $exclude_child - true oder false, entfernt untergeordnete Kategorien aus der Dropdown-Liste
- $sbc_style - true oder false, verwenden Sie das benutzerdefinierte 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); |
Nachdem wir unsere Standardeinstellungen festgelegt und zur Datenbank hinzugefügt haben, können wir die Funktion "get_option('entry-title')" von Wordpress in unserer Funktion config_page verwenden, damit unsere Werte in den Formularen wiedergegeben werden.
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"); |



Nachdem unsere Optionsseite die Daten aus der Datenbank verwendet, richten wir den Aktualisierungsprozess ein. Zunächst starten wir eine neue if-Anweisung, die überprüft, ob unsere Senden-Schaltfläche aktiviert ist. Als Nächstes vergleichen wir unser wpnonce, um zu überprüfen, ob der Benutzer die Seite besucht hat, bevor wir versuchen, die Optionen zu aktualisieren. Dann führen wir eine weitere if-Anweisung aus, um zu überprüfen, ob der Strom die Einstellungen ändern darf, indem wir die WP-Funktion "current_user_can('manage_options')" ausführen. Wenn dies nicht möglich ist, beenden wir das Skript.
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 |
}
|
Jetzt aktualisieren wir die zuvor definierten Variablen mit dem Eingabewert aus dem Formular. Da wir Kontrollkästchen für die Liste der ausgeschlossenen Kategorien verwenden, ist es am besten, eine andere if-Anweisung zu deklarieren und zu überprüfen, ob "post_category" (die von der WP-Funktion für die Liste angegebene ID) festgelegt ist. Wenn es vorhanden ist, nehmen wir seine Rohform und setzen es wieder in die Variable "$raw_excluded_cats" von früher ein, damit die Kontrollkästchen aktiviert bleiben. Wir werden dieselben Rückgabewerte auch verwenden, um ein "hübsches" durch Kommas getrenntes Array für die spätere Verwendung zu erstellen, indem wir am Anfang des Arrays einen zusätzlichen Wert hinzufügen (dies ist eine Korrektur für einen Fehler später in einer anderen Funktion) und dann implodiere das 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 |
}
|
Aufgrund der Natur von Kontrollkästchen haben sie nur dann einen Rückgabewert, wenn sie aktiviert sind. Daher müssen wir einen Fang schreiben, wenn sie nicht aktiviert sind. Dazu verwenden wir eine einfache if-Anweisung, die prüft, ob unsere Variablen leer sind (da das Formular keinen Rückgabewert enthält, mit dem es ausgefüllt werden kann). Wenn es leer ist, setzen wir den Wert auf "0" (falsch).
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 |
Jetzt besteht unser letzter Schritt darin, die Datenbank mit unseren neuen Werten mithilfe der Wordpress-Funktion "update_option('entry-title', 'new-value')" zu aktualisieren. Wir werden auch die Werte, die wir in die Datenbank einfügen, mit der Funktion mysql_real_escape_string() umschließen, um eine SQL-Injection zu verhindern.
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)); |
Unser Code Bisher:
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 |
?>
|
Formular erstellen
Nachdem wir unser Back-End eingerichtet und bereit für die Bereitstellung haben, ist es an der Zeit, das Front-End-Formular zu schreiben, das alle Besucher sehen und verwenden können. Damit unser Benutzer unser Formular an einer beliebigen Stelle auf seiner Website platzieren kann, werden wir unser Formular in eine neue Funktion mit dem Titel "sbc()" einschließen, die direkt außerhalb unserer Klassendeklaration platziert wird. Die ersten Code-Bytes, die wir hinzufügen müssen, deklarieren eine globale $wp_query und $post, damit wir später auf diese Funktionen zugreifen können, wenn wir dies wünschen, aber für unsere Zwecke werden wir sie nicht benötigen. Der nächste Schritt besteht darin, unsere Variablenwerte erneut aus der Datenbank abzurufen.
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 |
}
|
Sobald wir das getan haben, können wir eine weitere Variable namens "$list" erstellen, deren Wert die WP-Funktion wp_dropdown_categories($settings) ist (lesen Sie hier mehr zu dieser Funktion). In dieser Variablen "$settings" werden die meisten unserer Anpassungen angewendet.
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); |
Nachdem das Dropdown-Menü des Formulars konfiguriert wurde, können wir eine weitere Variable erstellen, "$form", die unser Formular-HTML über einen Hypertext-Präprozessor enthält. dann geben wir unsere neue Variable $form wieder.
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; |
Hinzufügen im benutzerdefinierten Styling
Zuvor hatten wir dem Benutzer die Möglichkeit gegeben, unser benutzerdefiniertes Styling für das Formular zu verwenden. Wenn diese Option im Einstellungsmenü aktiviert bleibt, müssen wir unser Stylesheet zur Kopfzeile hinzufügen. Der einfachste Weg, dies zu tun, besteht darin, eine neue if-Anweisung zu erstellen, die prüft, ob unsere Variable "$sbc_style" wahr ist (in unserem Code: 1). Innerhalb dieser Prüfung fügen wir eine neue Funktion "style_insert()" hinzu, die die URL zu unserem Stylesheet wiedergibt. Auch im if (aber außerhalb der Funktion) schreiben wir eine neue Aktion für "wp_head", um sie in unsere Funktion "style_insert()" einzufügen.
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 |
}
|
Erstellen Sie für unser Styling eine neue Datei mit dem Namen sbc-style.css und füllen Sie sie mit:
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 werden Sie feststellen, dass das Standard-Abwärtsdreieck in unserer Dropdown-Box fehlt. Dies liegt daran, dass wir das -khtml-appearance: none in der Dropdown-Liste, um zu verhindern, dass Safari das Thema "Schnee" erzwingt. Eine Möglichkeit, dies zu beheben, besteht darin, ein HTML-Zeichen zu verwenden, um das Dreieck zu simulieren, und es gibt zufällig ein sehr ähnliches Zeichen namens "∇ Nabla". Wir werden eine Kombination aus Leerzeichen, nicht unterbrechenden Leerzeichen und dieser Nabla in den Dropdown-Einstellungen verwenden, um dieses Problem zu beheben.
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); |



Rückgabe der Suchergebnisse
Sobald wir unser Formular erstellt haben, können wir endlich die Suchergebnisse abrufen, die wir unseren Besuchern geben möchten. Zu Beginn erstellen wir eine neue Funktion mit dem Namen return_only_selected_category(), in der wir eine neue if-Anweisung erstellen, die überprüft, ob unsere Schaltfläche zum Senden der Suche aktiviert ist. Darin müssen wir eine neue global $wp_query erstellen. Als nächstes nehmen wir die ausgewählte Kategorie zurück und platzieren sie in einer Variablen namens $desired_cat. Falls der Benutzer die Option für alle Kategorien ausgewählt hat, müssen wir den Wert "*" prüfen und auf "" zurücksetzen.
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 |
}
|
Jetzt müssen wir eine weitere Variable erstellen, $excluded, deren Wert die WP-Funktion get_categories() ist. Wir werden dieser Funktion 2 Argumente hinzufügen. Erstens ist "hide_empty=false", damit alle Kategorien in die Liste aufgenommen werden, und zweitens ist "exclude={$desired_cat}", damit alle Kategorien, aus denen der Benutzer Beiträge anzeigen möchte, aus der Liste entfernt werden.
1 |
|
2 |
$excluded = get_categories('hide_empty=false&exclude={$desired_cat}'); |
Sobald diese Variable festgelegt ist, können wir sie endlich so gestalten, dass nur Beiträge aus der ausgewählten Kategorie in den Ergebnissen angezeigt werden. Für diesen Effekt werden wir die Abfrage-Vars so ändern, dass Wordpress Beiträge aus jeder Kategorie entfernt, die wir auflisten (und es kommt einfach so vor, dass wir eine Variable voller Kategorien ausschließen müssen).
1 |
|
2 |
$wp_query->query_vars['cat'] = '-' . $excluded; |
Durch Hinzufügen eines Bindestrichs vor der Liste der Kategorien weisen wir Wordpress an, diese aus der Abfrage zu entfernen. Eine sehr effektive Methode für uns. Jetzt müssen Sie nur noch einen neuen WP-Filter für "pre_get_posts" hinzufügen, der in unserer neuen Funktion hinzugefügt wird.
1 |
|
2 |
// Highjack the search
|
3 |
add_filter('pre_get_posts', 'return_only_selected_category'); |
So fügen Sie unser Formular ein
1 |
|
2 |
<?php if(function_exists('sbc')){ |
3 |
sbc(); |
4 |
} else { ?> |
5 |
...your standard form code here... |
6 |
<?php } ?> |
Unser fertiger 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 |
?>
|