Incluir prazo de taxonomia personalizado em busca
-
-
Norcross,vocêpode adicionar algumfeedback à respostapropostaporjan?Vocêprovavelmenteestáprocurandopor umplugin quefaz otrabalho?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
-
Acabei abandonando oplano.Desde queeutinha criado 3funções depesquisa separadas (combaseem diferentesnecessidadesem determinadas áreas),todos osplugins quetestei quebrouisso.Nofinal,eu disse ao clienteparaincluirtermosno conteúdo seeles quisessempesquisável.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 respostas
- votos
-
- 2010-12-15
Eu recomendo o Pesquisartudo plugintambém,mas se você quiserimplementarisso usando afunção depesquisa do WP,aquiestá o código queestou usandonomeutema 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');
ébaseadonoplugin depesquisa detag: http://Projetos.jessehape.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
-
Isso é ótimo ... Comoesse códigopode sermodificadoparaexcluir umamatriz de IDs detaxonomia apartir dapesquisa?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
-
Deve-senotar que ofiltro retornaparaessesganchos aceita * 2 * argumentos;O segundoparatodoseles sendo ainstância _wp_query_ que épassadapor referência.Quaisquer verificaçõespara 'is_search ()' ou outras chamadas demétodo _wp_query_ (`is_search ()` 'is_home () `')`etc.) devem sempre ser chamados diretamentenainstância de consulta (porexemplo,`very->is_search ()` assumindo oOnome da variável deinstância é `$ consulta 'na assinatura de retorno de chamada)em vez dafunção demodelo que sempre se referirá à consultaprincipal,não a consulta que ofiltroestá sendoexecutado.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
-
Além disso,provavelmentenão é umaboaideiaparainjetar a string debusca de capital aberto diretamenteem uma consulta SQL ... [Leitura recomendada] (http://codex.wordpress.org/class_reference/wpdb#protect_queries_AGAINST_SQL_INJETTACKS)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
-
Eugostaria apenas de acrescentar queissotem um conflito com o WPMLporque o WPML Alredy usa 't'naparte dejunção,então usando algopersonalizadoem vez detr,tt et corrigeesteproblemaI 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 - Você comentou acima que é "Provavelmentenão é umaboaideiainjetar a string depesquisabruta disponível diretamenteem uma consulta SQL".Como acontecerianegandoesse risco?Eu li o link que vocêforneceu,masnãopôde ver comoisso se liga à resposta original.Muito obrigadoem.@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 A resposta acimamostra `get_search_query ()` usado diretamentenainstrução MySQL da cláusula WHERE.Este código é vulnerável aos ataques deinjeção SQL,onde qualquerpessoapodeexecutar consultas SQL arbitráriasem seu sitepassando-aspelo campo depesquisa.Obviamente,é assim que aspesquisasfuncionamem algumgrau,mas opontoimportante é queessaentradaprecisa serpreparada corretamenteparagarantir queela sejainterpretada comotermos depesquisae não declarações SQL.Isto é o que ométodo `$ WPDB-> Preparar () '' épara o qual é descritona dita leitura 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
-
@TheChewy Vocêtambémpodeencontrar algunsbonsexemplosnos documentospara `WPDB :: Preparar () aqui: https://developer.wordpress.org/reference/classes/wpdb/prepear/@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 Oi Evan,obrigadopelaentrada.Eu sounovopara ophpe o código WPpersonalizadoe issofoitão longepelaminha cabeça.Você seria capaz de duplicar o código com o `$ wpdb->preparar () 'adicionado senão émuito difícil?Eu acho que vai ser semanas antes de chegarperto deentenderessetipo de coisa.@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
Esta é apesquisapadrão WordPress?Porque aquele nãopareceincluirtaxonomias (nemmesmopadrão,como categoriase tags)napesquisa.O códigoprocuraem
post_title
epost_content
,mas se você quiserincluir qualquer outra coisa,você deve ligarpara ofiltroposts_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
Eutentei a solução de onetrickpony acima https://wordpress.stackexchange.com/a/5404/37612,que é ótimo,maseuencontrei uma questão lá,quenãofuncionouparamim,e eufaria umapequenamodificação:
- .
- Seeuprocureipor uma stringnotítulo dataxonomia -funcionamuitobem
-
Se ataxonomiativer caracteresespeciais,e. Com alemão "Umlauts" (Ö,ä,ü)e umaprocura de OE,AE,UE Insteda de usar o CHAR ESPECIAL - vocêprecisa adicionar apesquisana lesma dataxonomia -
OR t.slug LIKE '%".get_search_query()."%'
-
Seprocurar uma combinação de uma consulta depesquisae umfiltro detaxonomia -issotambémfuncionabem
-
Mas oproblema é,quando vocêtenta usar apenas ofiltro detaxonomia - ogancho depesquisa anexa uma string vaziapara a consulta senenhumtextoforpesquisadoe,poressemotivo,obtertodos ospostsno resultado,em vez de apenas aqueles dataxonomiafiltrada. Umainstrução simples se resolva oproblema. Então,todo o códigomodificado seriaeste (funcionaperfeitamentebem paramim!)
function custom_search_where ($ onde) { Global $ WPDB; if (is_search () &&get_search_query ()) $ where.="ou ((t.name como '%".get_search_query (). "%' out.Slug como '%".get_search_query (). "%')e {$ wpdb->posts} .post_status='Publicar') "; retornar $ onde; } função custom_search_join ($juntar) { Global $ WPDB; if (is_search () &&get_search_query ()) $junte-se.="Left adingue {$ wpdb->term_relationships} TR on {$ wpdb->posts} .id=tr.object_id Innerjunte {$ wpdb->term_taxonomy}tt ontt.term_taxonomy_id=tr.term_taxonomy_idinternamenteinterna $ wpdb-> Termos}t emt.term_id=tt.term_id "; retornar $juntar; } Função Custom_Search_Groupby ($ Groupby) { Global $ WPDB; //precisamos agruparno ID POST $groupby_id="{$ wpdb->posts} .id"; if (!is_search ()|| Strpos ($ Groupby,$ Groupby_ID)!==FALSE||!get_search_query ()) Retornar $ Groupby; //Groupbyestava vazio,use onosso if (! Strlen (Trim ($ Groupby))) Retornar $ Groupby_ID; //nãoestava vazio,anexando onosso Retornar $ 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
Eutenho omesmonível deinformação comojan. Eu sei que épossívelestender apesquisa compluginstambém.
Provavelmente Pesquisartudo (Plugin WordPress) É o que vocêestáprocurando.De acordo com a lista de recursos,agora suportataxonomiaspersonalizadas.
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.
-
+1parapesquisartudoplugin.Funciona comoesperadoe retornamais resultados do que apesquisapadrão do 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
Eutenho omesmoproblema acontecendo com oplugin do carrinho de WooCommerce. Meus resultados depesquisanãoestãoincluindo otermo detaxonomiapersonalizado,'product_tag',porquenão é umatagpós-padrão.Euencontrei uma soluçãoneste outrotópico de stackover sobre o assunto:
oexemplo de códigopor tkelly trabalhouparamim ao substituir otermo
author
em seuexemplocomproduct_tag
de acordo com asnossasnecessidadespara osplugins do carrinho.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
Eu achei a resposta da onetrickponypara ser ótima,mastrata qualquerpesquisa como um únicotermoe tambémnão lida com umafrase depesquisaincluída com aspas. Eumodifiquei seu código (especificamente,o
atom_search_where
função) umpoucopara lidar comessas duas situações. Aquiestá aminha versãomodificada de seu 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');
Eutenho duastaxonomiaspersonalizadas aplicadas a doistipospersonalizados.A lista determosnabarra lateralbem e listarátodas aspostagens associadas aele.Noentanto,se vocêpesquisar um dostermosespecíficos,elenãotraz umpost comessetermo.
Exemplo: http://dev.andrewnorcross.com/das/all-case-studies/. Procureportermo "pqri"
Eunão recebonada.Algumaideia?Eutentei usar váriosplugins depesquisa,maseles quebrammeusparâmetros depesquisapersonalizados ou simplesmentenãofuncionam.