Incluir término de taxonomía personalizado en la búsqueda
-
-
Norcross,¿puede agregar algunos comentarios a la respuestapropuestapor Jan?¿Probablementeestábuscando un complemento quefuncione?Nocross, can you add some feedback to the answer proposed by Jan? Are you probably looking for a plugin that does the job?
- 0
- 2010-11-06
- hakre
-
Terminé abandonandoelplan.Como había creado 3funciones debúsqueda separadas (basadasen diferentesnecesidadesen ciertas áreas),todos los complementos queprobé las rompieron.Alfinal,le dije al cliente queincluyeratérminosen el contenido si querían que sepudierabuscar.I ended up ditching the plan. Since I had created 3 separate search functions (based on different needs in certain areas), all the plugins I tested broke those. In the end, I told the client to include terms in the content if they wanted it searchable.
- 0
- 2010-11-13
- Norcross
-
6 respuestas
- votos
-
- 2010-12-15
También recomendaríael complemento Search Everything ,pero si deseaimplementarlo usando lafunción debúsqueda de WP,aquíestáel código queestoy usandoen mitema Atom:
// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23 function atom_search_where($where){ global $wpdb; if (is_search()) $where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')"; return $where; } function atom_search_join($join){ global $wpdb; if (is_search()) $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; return $join; } function atom_search_groupby($groupby){ global $wpdb; // we need to group on post ID $groupby_id = "{$wpdb->posts}.ID"; if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby; // groupby was empty, use ours if(!strlen(trim($groupby))) return $groupby_id; // wasn't empty, append ours return $groupby.", ".$groupby_id; } add_filter('posts_where','atom_search_where'); add_filter('posts_join', 'atom_search_join'); add_filter('posts_groupby', 'atom_search_groupby');
Sebasaen el complemento Tag-Search: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23
I would recommend the Search Everything plugin too, but if you want to implement this using WP's search function, here's the code I'm using in my Atom theme:
// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23 function atom_search_where($where){ global $wpdb; if (is_search()) $where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')"; return $where; } function atom_search_join($join){ global $wpdb; if (is_search()) $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; return $join; } function atom_search_groupby($groupby){ global $wpdb; // we need to group on post ID $groupby_id = "{$wpdb->posts}.ID"; if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby; // groupby was empty, use ours if(!strlen(trim($groupby))) return $groupby_id; // wasn't empty, append ours return $groupby.", ".$groupby_id; } add_filter('posts_where','atom_search_where'); add_filter('posts_join', 'atom_search_join'); add_filter('posts_groupby', 'atom_search_groupby');
It's based on the Tag-Search plugin: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23
-
Estoesgenial: ¿cómo sepuedemodificareste códigoparaexcluir unamatriz de ID detaxonomía de labúsqueda?This is great-- how can this code be modified to exclude an array of taxonomy IDs from the search?
- 1
- 2012-01-06
- HandiworkNYC.com
-
Cabe señalar que las devoluciones de llamada defiltroparaestosganchos aceptan * 2 * argumentos;el segundoparatodoselloses lainstancia de _WP_Query_ que sepasapor referencia.Cualquier verificación de `is_search ()` u otras llamadas almétodo _WP_Query_ (`is_search ()` `is_home ()`etc.) siempre deben serinvocadas directamenteen lainstancia de consulta (porejemplo,`$ query->is_search ()` asumiendoelelnombre de la variable deinstanciaes `$ query`en lafirma de devolución de llamada)en lugar de lafunción deplantilla que siempre hará referencia a la consultaprincipal,no a la consultapara la que seestáejecutandoelfiltro.It should be noted that the filter callbacks for these hooks accept *2* arguments; the 2nd for all of them being the _WP_Query_ instance which is passed by reference. Any checks for `is_search()` or other _WP_Query_ method calls (`is_search()` `is_home()` etc.) should always be called directly on the query instance (eg. `$query->is_search()` assuming the name of the instance variable is `$query` in the callback signature) rather than the template function which will always refer to the main query, not the query that the filter is running for.
- 0
- 2014-06-07
- Evan Mattson
-
Además,probablementeno sea unabuenaideainyectar la cadena debúsqueda sinprocesar disponiblepúblicamente directamenteen una consulta SQL ... [lectura recomendada] (http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks)Also, probably not a good idea to inject the raw publicly available search string directly into an SQL query... [recommended reading](http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks)
- 6
- 2014-06-07
- Evan Mattson
-
Solome gustaría agregar queestotiene un conflicto con WPMLporque WPML ya usa 'T'en laparte de unión,por lo que usar algopersonalizadoen lugar detr,tt yt solucionaesteproblemaI would just like to add that this has a conflict with WPML because WPML alredy uses 'T' in join part, so using something custom instead of tr, tt and t fixes this problem
- 0
- 2016-02-09
- Bobz
-
@EvanMattson: usted comentó anteriormente que "probablementeno sea unabuenaideainyectar la cadena debúsqueda sinprocesar disponiblepúblicamente directamenteen una consulta SQL".¿Cómo haríaparanegarese riesgo?Leíelenlace queproporcionó,peronopude ver cómo se vincula con la respuesta original.Muchasgracias Em.@EvanMattson — you commented above that it's "probably not a good idea to inject the raw publicly available search string directly into an SQL query." How would go about negating that risk? I read the link you provided but couldn't see how that links to the original answer. Many thanks Em.
- 1
- 2020-04-05
- The Chewy
-
@TheChewy la respuesta anteriormuestra `get_search_query ()` usado directamenteen la declaración MySQL de la cláusula WHERE.Este códigoes vulnerable a los ataques deinyección de SQL,donde cualquierapuedeejecutar consultas SQL arbitrariasen su sitiopasándolasporel campo debúsqueda.Obviamente,asíes comofuncionan lasbúsquedas hasta ciertopunto,peroelpuntoimportantees queestaentrada debeprepararse adecuadamenteparagarantizar que seinterprete comotérminos debúsqueda yno como declaraciones SQL.Estoespara lo queeselmétodo `$ wpdb->prepare ()` que se describeen dicha lectura recomendada@TheChewy the answer above shows `get_search_query()` used directly in the MySQL statement of the WHERE clause. This code is vulnerable to SQL injection attacks, where anyone can execute arbitrary SQL queries on your site by passing them through the search field. Obviously that's how searches work to some degree, but the important point is that this input needs to be prepared properly to ensure it is interpreted as search terms and not SQL statements. This is what the `$wpdb->prepare()` method is for which is described in said recommended reading
- 0
- 2020-04-19
- Evan Mattson
-
@TheChewytambiénpuedeencontrar algunosbuenosejemplosen los documentos de `wpdb ::prepare ()` aquí: https://developer.wordpress.org/reference/classes/wpdb/prepare/@TheChewy you can also find some good examples in the docs for `wpdb::prepare()` here: https://developer.wordpress.org/reference/classes/wpdb/prepare/
- 0
- 2020-04-19
- Evan Mattson
-
@EvanMattson Hola Evan,graciasporel aporte.Soynuevotantoen php comoen el código WPpersonalizado yeso seme hapasadopor la cabeza.¿Podrías duplicarel código conel `$ wpdb->prepare ()` agregado sinoes demasiado difícil?Creo quepasarán semanas antes de queme acerque a comprenderesetipo de cosas.@EvanMattson Hi Evan, thanks for the input. I'm new to both php and custom WP code and that has gone so far over my head. Would you be able to duplicate the code with the `$wpdb->prepare()` added if it isn't too hard? I think it'll be weeks before I get close to understanding that sort of thing.
- 1
- 2020-04-21
- The Chewy
-
- 2010-10-07
¿Esesta labúsquedaestándar de WordPress?Debido a que nopareceincluirtaxonomías (ni siquieraestándar,como categorías yetiquetas)en labúsqueda.El códigobuscaen
post_title
ypost_content
,pero si deseaincluir algomás,debe conectarse alfiltroposts_search
.Is this the standard WordPress search? Because that doesn't seem to include taxonomies (not even standard, like categories and tags) in the search. The code searches in
post_title
andpost_content
, but if you want to include anything else you should hook into theposts_search
filter. -
- 2013-09-08
Probé la solución de Onetrickpony arriba https://wordpress.stackexchange.com/a/5404/37612,lo cualesgenial,peroencontré unproblema allí,quenofuncionóparamí,y haría unapequeñamodificación:
- sibusqué una cadenaen eltítulo de lataxonomía,funcionamuybien
-
si lataxonomíatiene caracteresespeciales,p.ej. con "diéresis"en alemán (ö,ä,ü) y unobusca oe,ae,ueen lugar de usarel carácterespecial - debe agregar labúsquedaen labarra de lataxonomía -
OR t.slug LIKE '%".get_search_query()."%'
-
sibusca una combinación de una consulta debúsqueda y unfiltro detaxonomía,estotambiénfuncionabien
-
Peroelproblemaes que,cuandointentas usar soloelfiltro detaxonomía,elgancho debúsqueda agrega una cadena vacía a la consulta sino sebuscatexto,yporesa razón obtienes TODAS laspublicacionesen el resultado,en lugar de solo los de lataxonomíafiltrada. Un simpleenunciado IF resuelveelproblema. Entonces,todoel códigomodificado seríaeste (¡funcionaperfectamentebien paramí!)
function custom_search_where ($ where) { global $ wpdb; if (is_search () &&get_search_query ()) $ where.="OR ((t.name LIKE '%".get_search_query (). "%' Ot.slug LIKE '%".get_search_query (). "%') Y {$ wpdb->posts} .post_status='publicar') "; return $ donde; } function custom_search_join ($join) { global $ wpdb; if (is_search () &&get_search_query ()) $join.="LEFT JOIN {$ wpdb->term_relationships}tr ON {$ wpdb->posts} .ID=tr.object_id INNER JOIN {$ wpdb->term_taxonomy}tt ONtt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN { $ wpdb->terms}t ONt.term_id=tt.term_id "; return $ unirse; } function custom_search_groupby ($groupby) { global $ wpdb; //necesitamos agruparen ID depublicación $groupby_id="{$ wpdb->publicaciones} .ID"; if (!is_search ()|| strpos ($groupby,$groupby_id)!==false||!get_search_query ()) return $groupby; //groupbyestaba vacío,usaelnuestro if (! strlen (recortar ($groupby))) return $groupby_id; //noestaba vacío,agregaelnuestro return $groupby. ",". $groupby_id; } add_filter ('posts_where','custom_search_where'); add_filter ('posts_join','custom_search_join'); add_filter ('posts_groupby','custom_search_groupby');
I tried the solution of Onetrickpony above https://wordpress.stackexchange.com/a/5404/37612, which is great, but I found one issue there, which did not work for me, and I would make one small modification:
- if I searched for a string in the title of the taxonomy - it works great
if the taxonomy has special characters e.g. with german "Umlauts" (ö,ä,ü) and one searches for oe, ae, ue insteda of using the special char - you need to add the search in the slug of the taxonomy -
OR t.slug LIKE '%".get_search_query()."%'
if you search for a combination of a search query and a taxonomy filter - this also works fine
But the problem is, when you try to use only the taxonomy filter - the search hook append an empty string to the query if no text is searched for, and for that reason you get ALL posts in the result, instead of only those from the filtered taxonomy. A simple IF statement solves the problem. So the whole modified code would be this (works perfectly fine for me!)
function custom_search_where($where){ global $wpdb; if (is_search() && get_search_query()) $where .= "OR ((t.name LIKE '%".get_search_query()."%' OR t.slug LIKE '%".get_search_query()."%') AND {$wpdb->posts}.post_status = 'publish')"; return $where; } function custom_search_join($join){ global $wpdb; if (is_search()&& get_search_query()) $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; return $join; } function custom_search_groupby($groupby){ global $wpdb; // we need to group on post ID $groupby_id = "{$wpdb->posts}.ID"; if(!is_search() || strpos($groupby, $groupby_id) !== false || !get_search_query()) return $groupby; // groupby was empty, use ours if(!strlen(trim($groupby))) return $groupby_id; // wasn't empty, append ours return $groupby.", ".$groupby_id; } add_filter('posts_where','custom_search_where'); add_filter('posts_join', 'custom_search_join'); add_filter('posts_groupby', 'custom_search_groupby');
-
- 2010-11-06
Tengoelmismonivel deinformación que Jan. Sé quetambiénesposible ampliar labúsqueda con complementos.
Probablemente Buscartodo (complemento de Wordpress) es lo queestábuscando.Según la lista defunciones,ahora admitetaxonomíaspersonalizadas.
I have the same level of information like Jan. I know it's possible to extend search with plugins as well.
Probably Search Everything (Wordpress Plugin) is what you are looking for. According to the feature list, it now supports custom taxonomies.
-
+1parael complemento Search Everything.Funciona como seesperaba y devuelvemás resultados que labúsquedaestándar de Wordpress.+1 For Search Everything plugin. It works as expected and returns more results than standard Wordpress search.
- 0
- 2010-12-02
- PNMG
-
- 2012-12-08
Tengoelmismoproblema conel complemento de carrito de WooCommerce. Mis resultados debúsquedanoincluyeneltérmino detaxonomíapersonalizado,'product_tag',porquenoes unaetiqueta depublicaciónestándar.Encontré una soluciónen este otro hilo de StackOverflow sobreel asunto:
Elejemplo de código de tkelly funcionóparamí al reemplazareltérmino
author
en suejemploconproduct_tag
segúnnuestrasnecesidadespara los complementos del carrito.I have the same problem going on with the WooCommerce cart plugin.. My search results are not including the custom taxonomy term, 'product_tag', because it not a standard post tag. I found a solution in this other StackOverflow thread about the matter:
The code example by tkelly worked for me when replacing the term
author
in his example withproduct_tag
as per our needs for the cart plugins. -
- 2015-11-12
Encontré que la respuesta de onetrickponyesexcelente,perotrata cualquierbúsqueda como un solotérmino ytampocotrata con unafrase debúsquedaentre comillas. Modifiqué su código (específicamente,lafunción
atom_search_where
) unpocopara lidiar conestas dos situaciones. Aquíestámi versiónmodificada de su código:// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23 function atom_search_where($where){ global $wpdb, $wp_query; if (is_search()) { $search_terms = get_query_var( 'search_terms' ); $where .= " OR ("; $i = 0; foreach ($search_terms as $search_term) { $i++; if ($i>1) $where .= " AND"; // --- make this OR if you prefer not requiring all search terms to match taxonomies $where .= " (t.name LIKE '%".$search_term."%')"; } $where .= " AND {$wpdb->posts}.post_status = 'publish')"; } return $where; } function atom_search_join($join){ global $wpdb; if (is_search()) $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; return $join; } function atom_search_groupby($groupby){ global $wpdb; // we need to group on post ID $groupby_id = "{$wpdb->posts}.ID"; if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby; // groupby was empty, use ours if(!strlen(trim($groupby))) return $groupby_id; // wasn't empty, append ours return $groupby.", ".$groupby_id; } add_filter('posts_where','atom_search_where'); add_filter('posts_join', 'atom_search_join'); add_filter('posts_groupby', 'atom_search_groupby');
I found the answer from onetrickpony to be great but it treats any search as a single term and also won't deal with a search phrase enclosed with quotation marks. I modified his code (specifically, the
atom_search_where
function) a bit to deal with these two situations. Here is my modified version of his code:// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23 function atom_search_where($where){ global $wpdb, $wp_query; if (is_search()) { $search_terms = get_query_var( 'search_terms' ); $where .= " OR ("; $i = 0; foreach ($search_terms as $search_term) { $i++; if ($i>1) $where .= " AND"; // --- make this OR if you prefer not requiring all search terms to match taxonomies $where .= " (t.name LIKE '%".$search_term."%')"; } $where .= " AND {$wpdb->posts}.post_status = 'publish')"; } return $where; } function atom_search_join($join){ global $wpdb; if (is_search()) $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; return $join; } function atom_search_groupby($groupby){ global $wpdb; // we need to group on post ID $groupby_id = "{$wpdb->posts}.ID"; if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby; // groupby was empty, use ours if(!strlen(trim($groupby))) return $groupby_id; // wasn't empty, append ours return $groupby.", ".$groupby_id; } add_filter('posts_where','atom_search_where'); add_filter('posts_join', 'atom_search_join'); add_filter('posts_groupby', 'atom_search_groupby');
Tengo dostaxonomíaspersonalizadas aplicadas a dostipos depublicacionespersonalizadas.la lista detérminosen labarra lateralestábien yenumerarátodas laspublicaciones asociadas conella.Sinembargo,sibusca uno de lostérminosen específico,no aparece unapublicación conesetérmino.
Ejemplo: http://dev.andrewnorcross.com/das/all-case-studies/ Buscareltérmino "PQRI"
No obtengonada.¿Algunasideas?Intenté usar varios complementos debúsqueda,pero rompenmisparámetros debúsquedapersonalizados o simplementenofuncionan.