Inclure un terme de taxonomie personnalisé dans la recherche
-
-
Norcross,pouvez-vous ajouter quelques commentaires à la réponseproposéepar Jan?Êtes-vousprobablement à la recherche d'unplugin quifait letravail?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
-
J'aifini par abandonner leplan.Depuis quej'avais créé 3fonctions de recherche distinctes (basées sur desbesoins différents dans certains domaines),tous lesplugins quej'aitestés les ont cassés.Enfin de compte,j'ai dit au client d'inclure destermes dans le contenu s'il voulait qu'il soit consultable.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 réponses
- votes
-
- 2010-12-15
Je recommanderais également leplugin Recherchertout ,mais si vous souhaitez l'implémenteren utilisant lafonction de recherche de WP,voici le code quej'utilise dansmonthème 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');
Ilestbasé sur leplugin 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
-
C'estgénial - comment ce codepeut-il êtremodifiépourexclure untableau d'identifiants detaxonomie de la recherche?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
-
Il convient denoter que les rappels defiltrepour ces hooks acceptent les arguments * 2 *;le 2èmepourtous étant l'instance _WP_Query_ quiestpasséepar référence.Toute vérification de `is_search ()` ou d'autres appels deméthode _WP_Query_ (`is_search ()` `is_home ()`etc.) doittoujours être appelée directement sur l'instance de la requête (parexemple,`$ query->is_search ()`en supposant quelenom de la variable d'instanceest `$ query` dans la signature de rappel)plutôt que lafonction demodèle quiferatoujours référence à la requêteprincipale,pas à la requêtepour laquelle lefiltre s'exécute.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
-
Deplus,probablementpas unebonneidée d'injecter la chaîne de recherchebrute disponiblepubliquement directement dans une requête SQL ... [lecture recommandée] (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
-
Je voudrais simplement ajouter que cela a un conflit avec WPML car WPML utilise déjà 'T' dans lapartie dejointure,donc utiliser quelque chose depersonnalisé au lieu detr,tt ett résout ceproblèmeI 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 - vous avez commenté ci-dessus que cen'est "probablementpas unebonneidée d'injecter la chaîne de recherchebrute disponiblepubliquement directement dans une requête SQL".Comment éliminerait ce risque?J'ai lu le lien que vous avezfourni,maisje n'aipas vuen quoi cela renvoie à la réponse d'origine.Mercibeaucoup 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 réponse ci-dessusmontre `get_search_query ()` utilisé directement dans l'instruction MySQL de la clause WHERE.Ce codeest vulnérable aux attaquesparinjection SQL,oùn'importe quipeutexécuter des requêtes SQL arbitraires sur votre siteen lespassantpar le champ de recherche.Évidemment,c'est ainsi que les recherchesfonctionnent dans une certainemesure,mais lepointimportantest que cetteentrée doit êtrepréparée correctementpourgarantir qu'elleestinterprétée comme destermes de rechercheet non comme desinstructions SQL.C'est à cela que sert laméthode `$ wpdb->prepare ()` quiest décrite dans ladite lecture recommandée@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
-
@TheChewy vouspouvez égalementtrouver debonsexemples dans la documentation de `wpdb ::prepare ()`ici: 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 Salut Evan,mercipour la contribution.Je suisnouveau dans le code PHPet WPpersonnaliséet celam'atellement dépassé.Seriez-vous capable de dupliquer le code avec le `$ wpdb->prepare ()` ajouté si cen'estpastrop difficile?Jepense que celaprendra des semaines avant queje ne soisproche de comprendre cegenre de chose.@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
Est-ce la recherche WordPress standard?Parce que ne semblepasinclure detaxonomies (pasmêmestandard,comme les catégorieset lesbalises) dans la recherche.Le code recherche dans
post_title
etpost_content
,mais si vous souhaitezinclure autre chose,vous devez vous connecter aufiltreposts_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
J'aiessayé la solution d'Onetrickpony ci-dessus https://wordpress.stackexchange.com/a/5404/37612,ce quiestgénial,maisj'aitrouvé unproblème là-bas,quin'apasfonctionnépourmoi,et j'apporterais unepetite modification:
- sij'ai recherché une chaîne dans letitre de lataxonomie,celafonctionnetrèsbien
-
si lataxonomie a des caractères spéciaux,parexemple avec "Umlauts" allemands (ö,ä,ü)et on recherche oe,ae,ueinsteda d'utilisation du caractère spécial -ilfaut ajouter la recherche dans le slug de lataxonomie -
OR t.slug LIKE '%".get_search_query()."%'
-
si vous recherchez une combinaison d'une requête de rechercheet d'unfiltre detaxonomie,celafonctionne égalementtrèsbien
-
Mais leproblèmeest que,lorsque vousessayez d'utiliser uniquement lefiltre detaxonomie - le crochet de recherche ajoute une chaîne vide à la requête si aucuntexten'est recherché,et pour cette raison,vous obtenez TOUS lesmessages dans le résultat,au lieu de seulement ceux de lataxonomiefiltrée. Une simpleinstruction IF résout leproblème. Donctout le codemodifié serait ceci (fonctionneparfaitementbien pourmoi!)
function custom_search_where ($ where) { global $ wpdb; if (is_search () &&get_search_query ()) $ where.="OR ((t.name LIKE '%".get_search_query (). "%' ORt.slug LIKE '%".get_search_query (). "%') AND {$ wpdb->posts} .post_status='publier') "; retourner $ où; } 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->termes}t ONt.term_id=tt.term_id "; return $join; } function custom_search_groupby ($groupby) { global $ wpdb; //nous devons regrouper sur l'identifiant de l'article $groupby_id="{$ wpdb->messages} .ID"; if (!is_search ()|| strpos ($groupby,$groupby_id)!==false||!get_search_query ()) return $groupby; //groupby était vide,utilisez lenôtre if (! strlen (trim ($groupby))) return $groupby_id; //n'étaitpas vide,ajoutez lenôtre retourne $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
J'ai lemêmeniveau d'informations que Jan. Je sais qu'ilest égalementpossible d'étendre la recherche avec desplugins.
Tout rechercher (plugin Wordpress) estprobablement ce que vous recherchez.Selon la liste desfonctionnalités,ilprend désormaisen charge lestaxonomiespersonnalisées.
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.
-
+1pour leplugin Search Everything.Ilfonctionne commeprévuet renvoieplus de résultats que la recherche Wordpress standard.+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
J'ai lemêmeproblème avec leplugin depanier WooCommerce. Mes résultats de recherchen'incluentpas leterme detaxonomiepersonnalisée,'product_tag',car cen'estpas unebalise depublication standard.J'aitrouvé une solution dans cet autrefil de discussion StackOverflow à ce sujet:
L'exemple de code de tkelly afonctionnépourmoi lors du remplacement duterme
author
dans sonexempleavecproduct_tag
selonnosbesoinspour lesplugins depanier.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
J'aitrouvé la réponse de onetrickponyexcellente,maiselletraitetoute recherche comme un seultermeet netraitepasnonplus unephrase de rechercheentreguillemets. J'aimodifié unpeu son code (enparticulier,lafonction
atom_search_where
)pourfaireface à ces deux situations. Voicima versionmodifiée de son 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');
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');
J'ai deuxtaxonomiespersonnalisées appliquées à deuxtypes d'articlespersonnalisés.la liste destermes sur labarre latéraletrèsbien et listeratous lesmessages qui lui sont associés.Cependant,si vous recherchez l'un destermesen particulier,aucunmessage contenant cetermen'apparaît.
Exemple: http://dev.andrewnorcross.com/das/all-case-studies/ Rechercher leterme "PQRI"
Jen'obtiens rien.Desidées?J'aiessayé d'utiliser diversplugins de recherche,maisils cassentmesparamètres de recherchepersonnalisés oune fonctionnenttout simplementpas.