Spanish (Español) translation by Andrea Jiménez (you can also view the original English article)
Con una cantidad cada vez mayor de contenido creado en tu sitio de Wordpress, tus usuarios inevitablemente necesitarán buscar en tu sitio para encontrar ese artículo útil específico de hace mucho tiempo. Para ayudar a reducir los resultados de la búsqueda, te mostraré cómo codificar un plugin que le permita al usuario buscar según la categoría.
Este tutorial incluye un screencast disponible para los miembros de Tuts+ Premium.
El primer paso en el desarrollo de nuestro plugin es decidir el conjunto de características que tendrá, además de la cantidad de personalización disponible. Queremos que nuestro plugin tenga las siguientes características y permita la personalización completa del usuario:
- Reconfigura la búsqueda según la categoría seleccionada
- Lista desplegable de categorías
- Capacidad de ocultar categorías sin publicaciones de la lista
- Capacidad de excluir categorías secundarias de la lista
- Opción para desactivar nuestro estilo incorporado
- Capacidad de excluir categorías específicas de la lista
- Capacidad de usar valores personalizados en el cuadro de búsqueda
- Capacidad de utilizar un valor personalizado para la selección "En todas las categorías"
Creación del esqueleto para el plugin
Antes de que podamos hacer algo con nuestro plugin, primero necesitamos construir el esqueleto para que el plugin funcione. Comenzaremos creando una nueva carpeta en el directorio "plugins" de Wordpress (/wp-content/plugins) y la titularemos "search-by-category" (por convención, todas las carpetas de plugins deben estar todas en minúsculas y usar guiones en lugar de espacios para que al enlazar a archivos en las URL de la carpeta sean fácilmente legibles por el ojo humano). Crea un nuevo archivo PHP en la carpeta titulada "sbc.php", este archivo servirá como base para toda nuestra estructura de plugins. Después, rellena el plugin con la información de Wordpress requerida para que aparezca en nuestro panel WP-Admin.
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 |
?>
|



Configurar la página Opciones
Ya que Wordpress está reconociendo nuestro plugin, podemos comenzar nuestro desarrollo. Lo primero que tenemos que hacer es configurar una página de Opciones para que podamos dejar que el usuario configure nuestro plugin a su gusto. Cómo funciona esto es un proceso de tres pasos:
Primero creamos una clase para que todas nuestras configuraciones operen dentro.
1 |
|
2 |
if ( ! class_exists( 'SBC_Admin' ) ) { |
3 |
class SBC_Admin { |
4 |
|
5 |
}
|
6 |
}
|
En segundo lugar, ejecutamos una función para crear la página de configuración.
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 |
}
|
Configuración de la personalización
Ya que tenemos nuestra página de configuración, podemos comenzar a agregar nuestras opciones de configuración para que las apliquemos más adelante en el plugin. Para mostrar nuestra página de configuración tendremos que crear una nueva función llamada "config_page()" la cual rellenaremos con el resto del código de nuestra sección de administración. Primero, escribiremos el HTML para todas nuestras secciones.
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>
|
Notarás que ya estamos usando PHP para hacer referencia a las variables: $search_text, $focus, $hide_empty, $exclude_child, $sbc_style y $raw_excluded_cats (en la función "wp_category_checklist"). Crearemos y expandiremos estas variables en el siguiente paso.



Screencast completo
Agregar nuestras opciones a la base de datos
Ya que la página de administración está en funcionamiento, podemos comenzar a usarla para agregar opciones a la base de datos. Para hacer esto, simplemente crearemos una variable antes de "if ( ! class_exists( 'SBC_Admin' ) ) {" y luego usa la función de Wordpress "add_option('entry-title','value')" para insertarla en la tabla de wp_options de la base de datos. Esta es la lista de las variables que usaremos en nuestro plugin:
- $focus: el texto predeterminado que el espectador ve en la lista desplegable de selección
- $hide_empty: verdadero o falso, elimina categorías con 0 publicaciones del menú desplegable
- $excluded_cats: una matriz separada por comas de las categorías excluidas
- $raw_excluded_cats: matriz de las categorías excluidas
- $search_text: el texto predeterminado en el cuadro de búsqueda del formulario
- $exclude_child: verdadero o falso, elimina las categorías secundarias del menú desplegable
- $sbc_style: verdadero o falso, usa la hoja de estilo SBC personalizada
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); |
Ya que tenemos nuestros valores predeterminados establecidos y agregados a la base de datos, podemos usar la función "get_option('entry-title')" de Wordpress en nuestra función config_page para que nuestros valores se reflejen dentro de los formularios.
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"); |



Ahora que nuestra página Opciones está usando los datos de la base de datos, configuraremos el proceso de actualización. Para empezar, iniciaremos una nueva instrucción if comprobando si nuestro botón enviar está configurado. Después compararemos nuestro wpnonce para verificar que el usuario visitó la página antes de intentar actualizar las opciones. Luego ejecutaremos otra instrucción if para verificar y asegurarnos de que la corriente pueda cambiar la configuración ejecutando la función WP "current_user_can ('manage_options')", si no puede, entonces eliminaremos el 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 |
}
|
Ahora actualizaremos las variables que definimos anteriormente con el valor de entrada del formulario. Dado que estamos usando casillas de verificación para la lista de categorías excluidas, la mejor manera de obtener el retorno que queremos de ella es declarar otra instrucción if y verificar que "post_category" (el id dado a la lista por la función WP) está configurado. Si está presente, entonces tomaremos su forma sin procesar y colocar de nuevo en la variable "$raw_excluded_cats" de antes para que las casillas de verificación permanezcan marcadas. También usaremos esos mismos valores de retorno para crear una matriz "bonita" separada por comas para su uso posterior agregando un valor extra al inicio de la matriz (esto es una solución para un problema técnico más adelante en otra función) y luego implosionar la matriz.
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 |
}
|
Debido a la naturaleza misma de las casillas de verificación, solo tienen un valor de retorno si están marcadas, por lo que debemos escribir una captura para cuando no estén marcadas. Para hacer esto, usaremos una declaración if simple que verifique si nuestras variables están vacías (ya que no hay un valor de retorno del formulario para llenarlo), si está vacío, configuramos el valor en "0" (falso).
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 |
Ahora nuestro último paso es actualizar la base de datos con nuestros nuevos valores utilizando la función de Wordpress "update_option('entry-title','new-value')". También ajustaremos los valores que estamos insertando en la base de datos con la función mysql_real_escape_string() para ayudar a prevenir cualquier inyección de SQL.
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)); |
Nuestro código hasta ahora:
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 |
?>
|
Crear el formulario
Ahora que tenemos nuestro back-end todo configurado y listo para implementar, es hora de comenzar a escribir el formulario del front-end que todos los visitantes verán y usarán. Para que nuestro usuario pueda colocar nuestro formulario en el lugar que quiera de su sitio, encerraremos nuestro formulario dentro de una nueva función titulada "sbc()" colocada justo fuera de nuestra declaración de la clase. Los primeros bytes de código que necesitamos agregar son declarar un $wp_query global y $post para que podamos tener acceso a esas funciones si lo queremos más adelante, pero para nuestros propósitos no los necesitaremos. El siguiente paso es volver a obtener los valores de nuestras variables de la base de datos.
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 |
}
|
Una vez que hayamos hecho eso, podemos crear otra variable llamada "$list" con su valor siendo la función WP wp_dropdown_categories($settings) (lee más sobre esta función aquí). Esa variable "$settings" es donde se aplica la mayor parte de nuestra personalización.
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); |
Ya que la lista desplegable del formulario está configurada, podemos crear otra variable, "$form" que sostendrá nuestro formulario HTML a través de un preprocesador de hipertexto. Luego haremos eco de nuestra nueva variable $form.
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; |
Agregar el estilo personalizado
Anteriormente le dimos al usuario la opción de usar nuestro estilo personalizado para el formulario. Si dejaron esta opción habilitada en el menú de configuración, necesitamos agregar nuestra hoja de estilo al encabezado. La forma más fácil de hacerlo es crear una nueva instrucción if comprobando que nuestra variable "$sbc_style" sea verdadera (en nuestro código: 1). Dentro de esa comprobación, agregaremos una nueva función "style_insert()" que repite la URL de nuestra hoja de estilos. También en el if (pero fuera de la función), escribiremos en una nueva acción para "wp_head" para agregarla en nuestra función "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 |
}
|
En cuanto a nuestro estilo, crea un nuevo archivo llamado sbc-style.css rellénalo con:
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;} |



En Safari notarás que el triángulo descendente estándar falta en nuestro cuadro desplegable, esto se debe a que usamos -khtml-appearance: none en el menú desplegable para evitar que safari obligue a su tema "nieve". Una forma de solucionar esto es usar un carácter HTML para simular el triángulo, y resulta que hay uno muy similar llamado "∇ Nabla". Usaremos una combinación de espacios, espacios de no separación y este nabla en la configuración desplegable para solucionar este problema.
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); |



Devolver los resultados de la búsqueda
Una vez que tenemos nuestro formulario listo y funcionando, finalmente podemos comenzar a obtener los resultados de búsqueda que buscamos para nuestros visitantes. Para empezar, crearemos una nueva función llamada return_only_selected_category(), en la que crearemos una nueva instrucción if comprobando que nuestro botón de envío de búsqueda está configurado. Dentro de eso necesitamos crear un nuevo $wp_query global. A continuación, tomaremos el retorno de categoría seleccionado y lo colocaremos en una variable llamada $desired_cat. En caso de que el usuario seleccionara la opción para todas las categorías, necesitamos ejecutar una comprobación para el valor "*" y restablecerlo a "".
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 |
}
|
Ahora necesitamos crear otra variable, $excluded, cuyo valor es la función WP get_categories(). Agregaremos 2 argumentos a esta función. El primero es "hide_empty=false" para que todas las categorías se incorporen a la lista, y el segundo es "exclude={$desired_cat}" para que cualquier categoría de la que el usuario quiera ver las publicaciones se elimine de la lista.
1 |
|
2 |
$excluded = get_categories('hide_empty=false&exclude={$desired_cat}'); |
Una vez configurada esa variable, finalmente podemos hacerla para que solo los mensajes de la categoría seleccionada aparezcan en los resultados. Para este efecto, modificaremos las variables de consulta para que Wordpress elimine publicaciones de todas las categorías que enumeramos (y da la casualidad de que tenemos una variable llena de categorías para excluir).
1 |
|
2 |
$wp_query->query_vars['cat'] = '-' . $excluded; |
Al agregar un guión delante de la lista de categorías, le estamos diciendo a Wordpress que las elimine de la consulta. Un método muy eficaz para nosotros. Ahora lo único que queda por hacer es agregar un nuevo filtro WP para "pre_get_posts" agregando nuestra nueva función.
1 |
|
2 |
// Highjack the search
|
3 |
add_filter('pre_get_posts', 'return_only_selected_category'); |
Cómo insertar nuestro formulario
1 |
|
2 |
<?php if(function_exists('sbc')){ |
3 |
sbc(); |
4 |
} else { ?> |
5 |
...your standard form code here... |
6 |
<?php } ?> |
Nuestro código terminado
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 |
?>
|



