Taxonomie personnalisée WP_Query pour tous les termes d'une taxonomie?
5 réponses
- votes
-
- 2011-02-05
Rétrospectivement,j'aifait unmashup de suggestions MikeSchinkelet t31os.Ilestpossible d'injecter cela à la volée dans des requêtesexistantes,mais celanécessite WordPress 3.1:
Pluginpour obtenir unflux RSSpour les articles contenantn'importe quelterme d'unetaxonomie.
In retrospect, I've did a mashup of MikeSchinkel and t31os suggestion. It's possible to inject that to existing queries on the fly, but it needs WordPress 3.1:
Plugin to get an RSS Feed for posts containing any term from a taxonomy.
-
- 2011-12-05
J'ai rencontré une situation similaire Dave.Ce code afait l'affairepourmesbesoins.Cen'estpas l'option laplus légère aumonde,maisellefaitbien letravail:
// Get all term ID's in a given taxonomy $taxonomy = 'taxonomy_name'; $taxonomy_terms = get_terms( $taxonomy, array( 'hide_empty' => 0, 'fields' => 'ids' ) ); // Use the new tax_query WP_Query argument (as of 3.1) $taxonomy_query = new WP_Query( array( 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'id', 'terms' => $taxonomy_terms, ), ), ) );
J'espère que cela vous aidera,vous outoute autrepersonne à rencontrer leproblème.
Kevin
I encountered a similar situation Dave. This code did the trick for my purposes. It's not the leanest option in the world but it does the job well:
// Get all term ID's in a given taxonomy $taxonomy = 'taxonomy_name'; $taxonomy_terms = get_terms( $taxonomy, array( 'hide_empty' => 0, 'fields' => 'ids' ) ); // Use the new tax_query WP_Query argument (as of 3.1) $taxonomy_query = new WP_Query( array( 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'id', 'terms' => $taxonomy_terms, ), ), ) );
Hopefully this help you or anyone else experiencing the issue.
Kevin
-
Celam'a étéextrêmement utile.Merci @kevinlearynetThis was extremely helpful for me. Thanks @kevinlearynet
- 0
- 2012-10-22
- Tyrun
-
Encore relatif aujourd'huiStill relative today
- 0
- 2018-10-18
- user1676224
-
- 2016-01-29
Quelque chose comme celui-cipourraitfonctionner:
$ args=tableau ( 'post_type'=> 'publier', 'tax_query'=>tableau ( tableau ( 'taxonomy'=> 'votre_taxonomie_personnalisée', 'operator'=> 'EXISTE' ), ), ); $ query=new WP_Query ($ args);
Something like this might work:
$args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'your_custom_taxonomy', 'operator' => 'EXISTS' ), ), ); $query = new WP_Query( $args );
You are basically asking for any post assigned to any term within your_custom_taxonomy.
-
- 2010-11-06
Bonjour @Dave Morris:
Vous avez raison,WordPress décide que si vousn'avezpas determe,ilignorera simplement votretaxonomie.
Ilexiste trois (3) approchesprincipales que vouspouvezessayer:
Utilisez une requête SQL complète avec
$ wpdb- >get_results ()
,Obtenez une liste de
$post- > ID
s pourtous lesmessages de votretaxonomie,puistransmettez-lesen utilisant le'post__id'
argument,ouAnnoter le SQL utilisépar
WP_Query
avec l'un des hooks qui vouspermet d'ajouter un SQLINNER JOIN
référençant lestables detaxonomie .
J'essaie d'éviter le SQL complet dans WordPressjusqu'à ce que celane puissepas être aidé ou qu'il renvoie simplement une liste d'identifiants. Et dans ce cas,j'éviterais detirer une liste de
$post-ID
à utiliser avec l'argument'post__id'
car celapourrait rencontrer desproblèmes deperformanceset même desproblèmes demémoire si vous aviezbeaucoup demessages. Celanous laisse avec len ° 3.J'ai créé une classepour étendre
La classeWP_Query
appeléePostsByTaxonomy
qui utilise le hook'posts_join
'. Vouspouvez le voirici:PostsByTaxonomy étend WP_Query { var $posts_by_taxonomy; var $taxonomie; function __construct ($ args=array ()) { add_filter ('posts_join',array (& amp; $this,'posts_join'),10,2); $this- >posts_by_taxonomy=true; $this- >taxonomie=$ args ['taxonomie']; unset ($ args ['taxonomie']); parent :: requête ($ args); } functionposts_join ($join,$ query) { if (isset ($ query- >posts_by_taxonomy)) { global $ wpdb; $join.=& lt; & lt; & lt; SQL INNER JOIN {$ wpdb- >term_relationships} ON {$ wpdb- >term_relationships} .object_id={$ wpdb- >posts} .ID INNER JOIN {$ wpdb- >term_taxonomy} ON {$ wpdb- >term_taxonomy} .term_taxonomy_id={$ wpdb- >term_relationships} .term_taxonomy_id AND {$ wpdb- >term_taxonomy} .taxonomy='{$this- >taxonomie}' SQL; } return $join; } }
Vous appelleriez cette classe comme vous le voyez ci-dessous. L'argument
'taxonomie'
est obligatoire mais vouspouvezpassern'importe quel (tous?) des autresparamètres queWP_Query
attend également,comme'posts_per_page'
:$ query=new PostsByTaxonomy (tableau ( 'taxonomie'=> 'Catégorie', 'posts_per_page'=> 25, )); foreach ($ query- >postsen tant que $post) { echo "{$post- >post_title} \n"; }
Vouspouvez copier la classe
PostsByTaxonomy
dans lefichierfunctions.php
de votrethème,ou vouspouvez l'utiliser dans unfichier.php
d'unplugin que vous êtesen train d'écrire.Si vous souhaitez letester rapidement,j'aipublié une version autonome du code dans Gist que vouspouveztéléchargeret copier à la racine de votre serveur Weben tant que
test.php
,modifieren fonction de votre cas d'utilisation,puis demander à votrenavigateuren utilisant une URLtelle quehttp://example.com/test.php
.MISE À JOUR
Pour omettre lespostsfixes despostsinclus dans la requête,essayez ceci:
$ query=new PostsByTaxonomy (tableau ( 'taxonomie'=> 'Catégorie', 'posts_per_page'=> 25, 'caller_get_posts'=> vrai, ));
Ou s'ilestimportantpour vous que la classe
PostsByTaxonomy
n'incluejamais demessagespersistants,vouspouvez leplacer dans le constructeur:fonction __construct ($ args=array ()) { add_filter ('posts_join',array (& amp; $this,'posts_join'),10,2); $this- >posts_by_taxonomy=true; $this- >taxonomie=$ args ['taxonomie']; $ args ['caller_get_posts']=true//Pas depost-it unset ($ args ['taxonomie']); parent :: requête ($ args); }
MISE À JOUR 2
Après avoirpublié ce quiprécède,j'ai appris que 'caller_get_posts' serait obsolèteet que
'ignore_sticky_posts'
sera utilisé dans WordPress 3.1.Hi @Dave Morris:
You are correct, WordPress decides if you don't have a term they'll just ignore your taxonomy.
There are three (3) main approaches you could try:
Use a complete SQL query with
$wpdb->get_results()
,Get a list of
$post->ID
s for all posts in your taxonomy and then pass them using the'post__id'
argument, orAnnotate the SQL used by
WP_Query
with one of the hooks that let's you add a SQLINNER JOIN
referencing the taxonomy tables.
I try to avoid complete SQL in WordPress until either it can't be helped or it's simply returning a list of IDs. And in this case I'd avoid pulling a list of
$post-ID
s for use with the'post__id'
argument because it could run into performance issues and even memory problems if you had lots of posts. So that leaves us with #3.I've created a class to extend
WP_Query
calledPostsByTaxonomy
which uses the'posts_join
' hook. You can see it here:class PostsByTaxonomy extends WP_Query { var $posts_by_taxonomy; var $taxonomy; function __construct($args=array()) { add_filter('posts_join',array(&$this,'posts_join'),10,2); $this->posts_by_taxonomy = true; $this->taxonomy = $args['taxonomy']; unset($args['taxonomy']); parent::query($args); } function posts_join($join,$query) { if (isset($query->posts_by_taxonomy)) { global $wpdb; $join .=<<<SQL INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_relationships}.object_id={$wpdb->posts}.ID INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id={$wpdb->term_relationships}.term_taxonomy_id AND {$wpdb->term_taxonomy}.taxonomy='{$this->taxonomy}' SQL; } return $join; } }
You would call this class as you see below. The argument
'taxonomy'
is an required but you can pass any (all?) of the other parameters thatWP_Query
expects as well, such as'posts_per_page'
:$query = new PostsByTaxonomy(array( 'taxonomy' => 'category', 'posts_per_page' => 25, )); foreach($query->posts as $post) { echo " {$post->post_title}\n"; }
You can copy the
PostsByTaxonomy
class to your theme'sfunctions.php
file, or you can use it within a.php
file of a plugin you may be writing.If you want to test it quickly I've posted a self-contained version of the code to Gist which you can download and copy to your web server's root as
test.php
, modify for your use case, and then request from your browser using a URL likehttp://example.com/test.php
.UPDATE
To omit Sticky Posts from the posts included in the query, try this:
$query = new PostsByTaxonomy(array( 'taxonomy' => 'category', 'posts_per_page' => 25, 'caller_get_posts' => true, ));
Or if it is important to you that the
PostsByTaxonomy
class never include sticky posts you could put it into the constructor:function __construct($args=array()) { add_filter('posts_join',array(&$this,'posts_join'),10,2); $this->posts_by_taxonomy = true; $this->taxonomy = $args['taxonomy']; $args['caller_get_posts'] = true // No Sticky Posts unset($args['taxonomy']); parent::query($args); }
UPDATE 2
After posting the above I learned 'caller_get_posts' will be deprecated and
'ignore_sticky_posts'
will be used in WordPress 3.1.-
Mike,mercipour votre aide.Je suisincapable defairefonctionner celapour une raison quelconque.Ilne renvoiepas uniquement lesmessages avec destermes attribués àpartir demataxonomiepersonnalisée.Il sembletoujours renvoyer d'autresmessages.Cependant,ilne renvoiepastous lesmessages,doncilfait définitivement quelque chose ... Puis-je utiliser lafonction $ query-> have_posts ()pouritérer?Aucune de cesméthodesne semblefonctionnerpourmoi,detoutefaçon.Mike, Thanks for your help. I'm unable to get that to work for some reason. It's not returning only posts with terms assigned from my custom taxonomy. It always seems to return other posts. However, it doesn't return all posts, so it's definitely doing something... Am I able to use the $query->have_posts() function to iterate? Neither method seems to be working for me, either way.
- 0
- 2010-11-06
- Dave Morris
-
Ah,c'estintéressant.J'aitrouvé la requête dans lejournalmysql qui obtient les deuxmessages quej'attends,et celafonctionne.Maispour une raison quelconque,cinq articles reviennent lorsqueje boucle sur $ query->posts.La seule autre chose queje remarque,c'est quejuste après l'exécution de la requête demessages detaxonomiepersonnalisée,une autre requête s'exécute qui saisittrois autresmessages,par leurpost_id.Etpuisje suppose que les cinqmessages sontplacés dans un seultableau de résultats.Ah, this is interesting. I found the query in the mysql log that gets the two posts I'm expecting, and it works. But for some reason, five posts are coming back when I loop over $query->posts. The only other thing I notice is that directly after the custom taxonomy posts query runs, another query runs that grabs three more posts, by their post_id's. And then I guess all five posts are put into one results array.
- 0
- 2010-11-06
- Dave Morris
-
Jepense queje l'ai compris.Cette requêtepersonnalisée sembleinclure despublicationspersistantes,même siellesne fontpaspartie de cettetaxonomiepersonnalisée.Desidées sur lafaçon d'honorer correctement lespublicationspersistantes,ou dumoinspour les sortir de cette requêteparticulière?Merci,DaveI think I figured it out. This custom query seems to include sticky posts, even though they are not in that custom taxonomy. Any ideas on how to honor sticky posts properly, or at least to get them out of this particular query? Thanks, Dave
- 0
- 2010-11-06
- Dave Morris
-
Ehbien,ils sont * "collants" *,non?:) C'est un comportement étrange,je pense,mais si vous utilisez `caller_get_posts=1`et ils devraient disparaître: http://codex.wordpress.org/Function_Reference/query_posts#Sticky_Post_Parameters J'espère que celat'aides.Well they are *"sticky"*, right? :) It's weird behavior, I think, but if you use `caller_get_posts=1` and they should go away: http://codex.wordpress.org/Function_Reference/query_posts#Sticky_Post_Parameters Hope this helps.
- 0
- 2010-11-06
- MikeSchinkel
-
Que `if (isset ($ query->posts_by_taxonomy))`est unebelle astucepour combiner laméthodologie orientée objet avec laméthodologie hook de WordPress.That `if(isset($query->posts_by_taxonomy))` is a nice trick to combine the object-oriented methodology with the hook methodology of WordPress.
- 0
- 2010-11-06
- Jan Fabry
-
@Jan Fabry - Oui,merci!Ilne m'afallu qu'environ 2 ans d'essaiset d'erreurs avant que celane me vienne à l'esprit.Bien sûrmaintenant cela semble évident ... :)@Jan Fabry - Yes, thanks! It only took me about 2 years of trial-and-error before it occurred to me. Of course now it seems obvious... :)
- 0
- 2010-11-06
- MikeSchinkel
-
Ça amarché!Mercibeaucouppour votre aide.J'aime apprendre denouvelles astuces WordPress,en particulier celles OO.That worked! Thanks so much for your help. I like learning new WordPress tricks, especially OO ones.
- 0
- 2010-11-07
- Dave Morris
-
@Dave Morris - Vous êtes lesbienvenus.BTW,je viens d'apprendre qu'il s'appellera ``ignore_sticky_posts '' dans WP 3.1.@Dave Morris - You are welcome. BTW, I just learned it will be called `'ignore_sticky_posts'` in WP 3.1.
- 0
- 2010-11-07
- MikeSchinkel
-
@MikeSchinkel Qu'enest-il de lapagination,celafonctionnebien mais lapagination de cette requêtene fonctionnepas commeelle le devrait dansmon cas ... http://wordpress.stackexchange.com/q/57884/12261@MikeSchinkel What about the pagination, this is works fine but the pagination for this query not working as it should in my case... http://wordpress.stackexchange.com/q/57884/12261
- 0
- 2012-07-09
- Ajay Patel
-
C'est unebelle astuceet çamarchetoujours!Mais qu'enest-il sije voulaisinclure untableau detaxonomies?2 ou 3taxonomies,que devons-nousmodifier avec la requête?That is a nice trick and it still works! However what about if I wanted to include an array of taxonomies? 2 or 3 taxonomies, what should we modify with the query?
- 0
- 2015-10-29
- MacLover
-
- 2010-11-05
Vous devriez simplementpouvoir définir lataxonomieet annulerpourinclure unterme.
Parexemple.
<?php $your_query = new WP_query; $your_query->query( array( 'taxonomy' => 'your-taxonomy-name' ) ); ?>
Ce qui serait àpeuprèsidentique à la requêteexécutéepar une archive detaxonomie.
You should just be able to set the taxonomy and negate to include a term..
Eg.
<?php $your_query = new WP_query; $your_query->query( array( 'taxonomy' => 'your-taxonomy-name' ) ); ?>
Which would pretty much be the same as the query a taxonomy archive performs.
-
Celane marchepas.That doesn't work.
- 0
- 2010-11-05
- Dave Morris
-
La ligne 1432 de query.php vérifie si lataxonomie OU letermeest vide,donc vousne pouvezpas simplementne paspasser un slug ... D'autresidées?Line 1432 of query.php checks whether taxonomy OR term are empty, so you can't just not pass a slug... Any other ideas?
- 0
- 2010-11-05
- Dave Morris
-
@t31os - C'était aussi lapremière réactionpossible;J'en aifaittrébucherplus d'unefois depuis quej'oublietoujours.Mais @Dave Morris a raison;si cen'estpas unepairetaxonomie/terme alors `WP_Query` lajette simplement.@t31os - That was might first reaction as well; I've actually been tripped up by it more than once since I keep forgetting. But @Dave Morris is right; if it's not a taxonomy/term pair then `WP_Query` just throws it away.
- 0
- 2010-11-06
- MikeSchinkel
-
Wow,je ne savaispas ça,c'est unpeuidiot vraiment ... leçon apprise ... :) Jem'attendais àmoitié à agir comme desparamètresmeta_key/meta_value (jene saispaspourquoi) ..Wow, i didn't know that, that's a bit silly really... lesson learned... :) I half expected to act like meta_key / meta_value parameters (i don't know why)..
- 0
- 2010-11-06
- t31os
-
@t31os - Ouais,`WP_Query`n'estmalheureusementpasimplémenté d'unemanière aussi élégante.C'estpresque 1 200 lignes de cas spéciaux codésen dur.@t31os - Yup, `WP_Query` is unfortunately not implemented in such an elegant manner. It's almost 1200 lines of hard-coded special cases.
- 7
- 2010-11-06
- MikeSchinkel
-
"près de 1 200 lignes de cas spéciaux codésen dur."... çam'afait lol,j'ai dû +1 le commentaire ...;)"almost 1200 lines of hard-coded special cases." ... that made me lol, had to +1 the comment... ;)
- 3
- 2010-11-06
- t31os
Existe-t-il unmoyen simple de rechercher des articlesbalisés avec unterme d'unetaxonomieparticulière?
Je connais cettetechnique:
Maisje voudrais soitpasser un caractèregénérique à laplace determ_slug,soitpeut-êtrejuste une chaîne vide.Ensuite,celame donneraittous lesmessages qui sontmarquésparn'importe quelterme de cettetaxonomie,pas seulement unterme spécifique.
Mercipour votre aide, Dave