En utilisant wp_query, est-il possible de classer par taxonomie?
10 réponses
- votes
-
- 2011-04-08
Non,iln'estpaspossible de classerpartaxonomie,car d'un certaintype depoint de vue,celan'apasbeaucoup de sens.
Lestaxonomies sont desmoyens de regrouper des éléments. Donc,l'intérêt d'avoir unetaxonomie sur lespostes serait vraiment d'avoir destermes dans cettetaxonomie qui sontpartagésentre lespostes. Si unetaxonomie avait destermes quin'étaient utilisés que sur un seul article chacun,cela rendrait lataxonomieinutile. Et si lestermes étaientpartagés commeils devraient l'être,alors les commanderne produirait rien departiculièrement utile.
Ce que vous devriez utiliser dans unetelle situation,c'est lepostmeta. Vouspouvez commanderparmessagemeta,et c'est unique à chaque article.
Edit: Cela dit,vouspouvez classerpartaxonomieen créant une requête SQLpersonnalisée à l'aide d'unfiltre,vousne pouveztout simplementpas lefaire àpartir d'une WP_Querynonmodifiée: http://scribu.net/wordpress/sortable-taxonomy-columns.html
Cependant,si vous devez recourir à cegenre de chose,alors la structure de conception de vos donnéesesterronéeen premier lieu. Les «termes» de lataxonomiene sontpas des «données» réelles. Lestermeseux-mêmesn'ont aucune significationintrinsèque,cene sont que des étiquettespour legroupeparticulier qu'ils décrivent. Si vous lestraitez comme des données significatives,vous avez un défaut de conception sous-jacent.
Lestaxonomies regroupent des élémentsen leur attribuant destermes. Ce regroupementesttout l'intérêt destaxonomies,lestermesne sont que dejolis visages sur legroupement. Si vous avez desmétadonnées significatives à attribuer à unepublication,vous devriez utiliser laméta depublication à laplace. Et que vous pouvez commanderpar,parce que laméta depublication utilise à lafois des cléset des valeurspour stocker desinformations. Avec unetaxonomie,vousne stockezen réalité que les clés,leurs valeurs étant lespublications regroupéespar ceterme.
Les choses sontplusfaciles à longterme si vous utilisez labonne approche. Même sije ne dispas que vousne pouvezpasfaire quelque chose d'étrange avec lataxonomie,vous vous compliquez simplement les choses à longtermeen l'utilisantmal.
No, it is not possible to order by taxonomy, because from a certain type of standpoint, that doesn't actually make much sense.
Taxonomies are ways to group things together. So the point of having a taxonomy on posts would really be to have terms in that taxonomy that are shared between posts. If a taxonomy had terms that were only used on one post each, then that would make the taxonomy kind of pointless. And if the terms were shared like they should be, then ordering by it wouldn't produce anything particularly useful.
What you should be using in such a situation is the post meta. You can order by post meta, and it's unique to each post.
Edit: That said, you can order by taxonomy by making a custom SQL query using a filter, you just can't do it from a unmodified WP_Query: http://scribu.net/wordpress/sortable-taxonomy-columns.html
However, if you're having to resort to doing this sort of thing, then your data design structure is wrong in the first place. "Terms" in the taxonomy are not actual "data". The terms themselves have no inherent meaning, they're just labels for the particular grouping that they're describing. If you're treating them as meaningful data, then you have an underlying design flaw.
Taxonomies group things by assigning terms to them. That grouping is the whole point of taxonomies, the terms are just pretty faces on the grouping. If you have meaningful metadata to assign to a post, then you should be using the post meta for it instead. And that you can order by, because post meta uses both keys and values to store information. With a taxonomy, you're really only storing keys, with their values being the posts grouped together by that term.
Things are easier in the long run if you use the correct approach for it. While I'm not saying that you can't do something strange with taxonomy, you're just making things harder for yourself in the long run by using it wrong.
-
Bonjour Otto,mercipour la réponse.Je comprends votrepoint de vueet peut-être queje vais dans lemauvais sens.Dansmonexemple un site d'émissions detélévision,j'ai unetaxonomiepour la série 1,la série 2,la série 3etc. Ainsije peux regroupertoutes les différentes émissions detélévisionparnuméro de série.Ensuite,j'ai lamême chosepour les épisodes,l'épisode 01,l'épisode 02,etc. Ce queje voudrais,c'est que lors de l'affichage d'une liste detous les épisodes,l'ordrepar épisodeet par série.Je vais analyserpuisposter desmétaet des champspersonnalisés.Merci Otto.Hello Otto, thank you for the answer. I see your point and maybe I am going the wrong way with this. In my example a site of tv shows, I have taxonomy for series 1, serie 2, serie 3 etc.. So I can group all the different tv shows by series number. Then I have the same for episodes, Episode 01, Episode 02, etc.. What I would like is when showing a list of all the episodes to be order by episode and serie. I will analyse then post meta and custom fields. Thank you Otto.
- 0
- 2011-04-08
- yeope
-
@yeope votretaxonomie doit être sérieet vostermes doivent être série 1,série 2,etc. Avec les épisodes,je suppose qu'une série contientplusieurs épisodes afin qu'ellepuisse utiliser lamêmetaxonomie,«série»et sielles sont hiérarchiques,l'épisode 1,l'épisode 2,etc. aurait letermeparent "série x".Ensuite,vouspouvezinterroger une sérieentière dans l'ordre avec les épisodes correspondant là oùils devraient.@yeope your taxonomy should be series and your terms should be series 1, series 2 etc. With episodes I'm assuming a series contains multiple episodes so it could use the same taxonomy, "series" and if they are hierarchal then episode 1, episode 2 etc would have the parent term "series x". Then you could query a whole series in order with the episodes falling in line where they should.
- 0
- 2011-04-08
- Chris_O
-
@Chris_O Je vois,vouspourriez être sur l'argent là-bas!Le seulproblème queje voisest lefait de devoir répéter lestermes "Episode 1","Episode 2"pour chaque série.Nepaspouvoirnonplus regroupertous les épisodes 1pasen fonction de la série,maisje pense qu'il y aprobablement unmoyen de contourner cela.Merci Chris_O@Chris_O I see, you might be on the money there! The only problem I can see is the fact of having to repeat the terms "Episode 1", "Episode 2" for each series. Also not being able to group all episodes 1 not depending on the series, but I think there is probably a way around it. Thank you Chris_O
- 0
- 2011-04-08
- yeope
-
L'utilisation d'unetaxonomiepour les épisodesn'apasbeaucoup de sens,en fait,car le regroupementest sans valeur.Pensez-y,si vous avez "épisode 1" commeterme,vous regroupez l'épisode 1 avectous les autres épisodes 1 detoutes les autres émissions detélévision.Lesnuméros d'épisodeet de série ontplus de sensen tant quepost_meta,carils sont spécifiques à cette émissionparticulièreet ne sontpas utilesen tant quegroupe.Lenom de l'émissiontélévisée serait utile commeterme dans unetaxonomie d'émissionstélévisées,car vous regroupez alors l'émission dans sonensemble.Using a taxonomy for episodes doesn't make much sense, actually, because the grouping is worthless. Think about it, if you have "episode 1" as a term, then you're grouping episode 1 with every other episode 1 from every other TV show. The episode and series numbers make more sense as post_meta, because they're specific to that particular show, and not useful as a group. The name of the TV show would be useful as a term in a tv-show taxonomy, because then you're grouping the show as a whole together.
- 2
- 2011-04-15
- Otto
-
Mais unetaxonomiepour les séries _kinda_fonctionne,mais uniquementparce qu'elle regroupe des émissions dans une saison ou quelque chose dugenre,bien que vous deviez également l'interroger avec lataxonomie des émissions detélévision.Dans unetelletaxonomie de séries,vostermes seraient 1,2,3,ce qui représente lenuméro de la saison dans laquelle setrouvait l'émission. Mais vous voudrieztoujours que cetteinformation soitpostmetaplus,car vous souhaitez commanderparelle.Et comme vouspouvez égalementinterroger surpostmeta,celan'a aucun sens de le dupliqueren tant quetaxonomie.But a taxonomy for series _kinda_ works, but only because it groups together shows in a season or something, although you'd have to query it with the tv-show taxonomy as well. In such a series taxonomy, your terms would be 1, 2, 3, which represent the season number that the show was in. But you'd still want this info as postmeta more, since you want to order by it. And since you can query on postmeta too, it makes no real sense to duplicate it as a taxonomy.
- 0
- 2011-04-15
- Otto
-
@Otto,à lafin je suis allé avec des champspersonnalisés :) C'étaitplus logique.@Otto, in the end I went with custom fields :) It made more sense.
- 0
- 2011-05-04
- yeope
-
Otto apoursuivi avec un article deblogintéressant: [Quand (nepas) utiliser unetaxonomiepersonnalisée] (http://ottopress.com/2011/when-to-not-use-a-custom-taxonomy/).Otto followed this up with an interesting blog post: [When to (not) use a Custom Taxonomy](http://ottopress.com/2011/when-to-not-use-a-custom-taxonomy/).
- 1
- 2011-05-05
- Jan Fabry
-
@otto Merci departager cela,c'est vraimentbien de lire unpeuplus sur lestaxonomieset leurs usages.Plusprécisément,je suisintéressé à connaître votre opinion sur une situation comme celle décrite dans l'article [Colonnes detaxonomietriable] (http://scribu.net/wordpress/sortable-taxonomy-columns.html).Quelle serait lameilleure solution lorsqueje veux à lafoispouvoirinterrogertous les articles dans unegamme de couleurs,mais aussitrierpar couleur?Peut-être que ce seraitmieux comme question séparée ...@otto Thanks for sharing this, it's really good to read a little more into taxonomies and their usages. Specifically I'm interested in knowing your thoughts on a situation like that described in the [Sortable Taxonomy Columns](http://scribu.net/wordpress/sortable-taxonomy-columns.html) post. What would be the best solution when I want to both be able to query all posts in a colour range, but also want to sort by colour? Maybe this would be best as a separate question...
- 0
- 2013-12-20
- Gaffen
-
Si vous vouleztrierparelle,alors ce devrait vraiment être uneméta au lieu d'unetaxonomie.Letripartaxonomien'apasbeaucoup de sens,demanière réaliste.If you want to sort by it, then it should really be meta instead of a taxonomy. Sorting by taxonomy doesn't make a whole lot of sense, realistically.
- 0
- 2013-12-21
- Otto
-
Merci @Otto.Bien queje ne soispas d'accord avec votre affirmation: "Cependant,si vous devez recourir à cegenre de chose,la structure de conception de vos donnéesestincorrecteen premier lieu." ... Ilpourrait être utile depouvoir utiliser leliste despublicationsparterme de catégorie côté administrateur ...Thank you @Otto. Though I disagree with your statement: "However, if you're having to resort to doing this sort of thing, then your data design structure is wrong in the first place."... It could be useful to be able to resort the post list by category term on the admin side...
- 0
- 2017-05-23
- ClemC
-
@ClemC Celan'apasbeaucoup de sens.Lespublicationspeuvent avoirplusieurs catégories.Par quoitriez-vous?Quels sont vos critères detri secondaires lorsque deux articles ont lamême catégorie?C'est legenre deproblème que vous rencontrez,lestaxonomiesne sont que desgroupements,le «terme»estjuste unjoli visage sur cegroupement,cen'estpas lapartieimportante.Lapartieimportanteest legroupe lui-même.Vousne trieriezpas lesnoms d'animauxpar ordre alphabétique selon leurtaxonomie linnéenne.Celane vous aidepas.@ClemC That doesn't make a lot of sense. Posts can have multiple categories. What are you sorting by? What is your secondary sort criteria when two posts have the same category? That's the sort of problem you run into, taxonomies are just groupings, the "term" is just a pretty face on that grouping, it's not the important part. The important part is the group itself. You would not sort animal names alphabetically by their Linnaean taxonomy. Doesn't help you any.
- 0
- 2017-05-24
- Otto
-
Salut @Otto,vous avez unpoint.J'aipris comme référence le cas demonprojet actuel quiest assezparticulier ... Un CPT (film)n'autorisant qu'un seulterme detaxonmypersonnalisé (festival) avec desboutons radiopour sa sélection.L'ordrepar défaut de la liste CPTestparterme (festival),ce qui dans ce casparticulierest assez logique,non?Jene peuxpaspenser à unemeilleure approche de la "conception de données" ... J'aiimplémenté des "festivals" commetaxonomieparce que les seules données dontils ontbesoin sont leur descriptionet regroupent logiquement des "films". PS: Désolépourmon anglais.Hi @Otto, you have a point. I took as reference the case of my current project which is particular enough... A CPT (movie) allowing only a single custom taxonmy's (festival) term with radio buttons for its selection. The CPT list default order is by term (festival) which in this particular case is logic enough, no? I can't think of a better approach about the "data design"... I have implemented "festivals" as a taxonomy because the only data they need is their description and it's logically grouping "movies". PS: Sorry for my english.
- 0
- 2017-05-25
- ClemC
-
Oui,c'estjuste,mais alors c'est ungroupe.Vous regroupez les choses.Que signifie alors «trierpar» dans untel contexte?Si vous avez untas de choses dans lemêmegroupe,alors vouspouvez «sélectionnerpar» cegroupe,et c'est logique,mais «trier»est quelque chose detotalement différent.Voustriezpar champs qui ont des valeurs différentes,paspar champs qui onttous lesmêmes valeurs.Yes, fair enough, but then it is a group. You're grouping things together. What does "sort by" mean in such a context then? If you have a bunch of things in the same group, then you can "select by" that group, and that makes sense, but "sort" is something totally different. You sort by fields that have different values, not by fields that all have the same values.
- 0
- 2017-05-25
- Otto
-
Désolé @Otto,je ne remarque quemaintenant votre réponse ... Je suistotalement d'accord avec vospoints sémantiqueset votre logique.Mais dansmon contexte,«trierpar» seraitprincipalement une question **ergonomique **.** Visuellement ** regrouper lesprojectionspar "festival"peut aider demanière assezimportante l'utilisateur à obtenir un CV visuelbasé sur lefacteur leplusimportantpour lui,cecien un coup d'œil.Ainsi,je ne suispas sûr depouvoir yparvenir autrement qu'en "triant" ce qui,je suis d'accord,n'estpas unterme approprié ...Sorry @Otto, I only now notice your answer... I totally agree with your semantic points and logic. But in my context, "sorting by" would be mainly an **ergonomic** matter. **Visually** grouping the projections by "festival" may help importantly enough the user to get a visual resume based on the most important factor for him, this at a glance. Thus, not sure I can achieve this somehow else than by "sorting" which I agree is not an appropriate term...
- 0
- 2017-08-19
- ClemC
-
- 2014-07-28
La réponse acceptéepour cette questionestinacceptable. Ilestillogique de supposer que la commandepartaxe «n'apas de sens». La réponse qu'il a donnéen'apas de sens.
Pensez à avoir untype demessage demenu. Ensuite,vous avez unetaxepersonnalisée de "FoodCategories". Lataxe FoodCategories comprend lestermes «petit-déjeuner»,«déjeuner»et «dîner». Si vous soumettez une requête à l'aide duparamètretax_query,vous disposez désormais d'unjeu de résultats avectous lestermes,maisils sont classéspar date depublication.
Afin d'obtenir lebon ordreparmi ceux-ci,par rapport à leurstermes,puis de les afficher sur lefront-end demanière appropriéeen séparant lespublicationsen leurs différentes catégories,vous devezparcourir l'ensemble de résultats,puisinterroger chaqueindividupublier dans l'ensemble de résultatspourtrouver sestermeset comparer auterme actuel,filtrer dans untableauet continuertout au long. Ensuite,vous devez ànouveauparcourir lenouveautableaupour l'affichage. Cen'estpasproductif.
Ce seraitbien si WP avait une option orderby "tax__in" commeil lefaitpour "post__in",mais comme cen'estpas le cas,vous devez soitfaire leprocessus ridicule ci-dessus;personnalisez vous-même la requête aumoyen dufiltre 'posts_orderby'et dufiltre 'posts_join' afin d'ajuster laméthode orderbyet d'ajouter leterme à l'ensemble de résultats,respectivement; ou vous devez créer unenouvelle requêtepour chaqueterme que vousfiltrez dans les sections html relatives à cestermes.
Leplusefficace serait de changer la chaîne de requête aumoyen defiltres. Leplus simple serait defairetrois requêtes distinctes. L'API WP doitgérer letripartaxe outoutparamètre de requête restrictif. Si vous limitez une requêteen fonction de certaines conditions,il y a uneforteprobabilité quebeaucoup d'entreeux aientbesoin de commander selon cesmêmes conditions.
The accepted answer for this question is unacceptable. It is illogical to assume that ordering by tax "doesn't make sense". The answer he gave doesn't make sense.
Consider having a menu post type. Then you have a custom tax of "FoodCategories". The FoodCategories tax has "Breakfast", "Lunch" and "Dinner" terms. If you submit a query utilizing the tax_query param, you now have a result set with all of the terms, however they are ordered by post date.
In order to get the correct order out of these, relative to their terms, and then to display on the front end appropriately by separating the posts into their various categories, you have to loop through the result set, then query each individual post within the result set to find it's terms and compare to the current term, filter into an array and continue throughout. Then you have to again loop through the new array for display. This is not productive.
It would be nice if WP had a "tax__in" orderby option as it does a "post__in" one, but since it does not, you either have to do the above ridiculous process; customize the query yourself by way of 'posts_orderby' filter and 'posts_join' filter in order to adjust the orderby method and add the term to the result set, respectively; or you have to make a new query for each term you are filtering for within the html sections relative to those terms.
The most efficient would be to change the query string by way of filters. The easiest would be to do three separate queries. The WP API should be handling ordering by tax, or any restrictive query parameters. If you are restricting a query based on certain conditions, there is a high probability that many will have need to order by those same conditions.
-
Désolé,mais vous voustrompez.Le classementpartaxonomien'apasnonplus de sens dans votre cas.Que voulez-vousmontrer?Tous lespetits déjeuners d'abord,suivis detous les dîners,puistous les déjeuners?Vous devez sélectionner ce que vous voulezet l'ordre dans lequel vous le souhaitez,mais lataxonomien'est qu'une étiquette de regroupement.Cene sontpas des «données» significatives que vous devriez commander.Si c'est le cas,alors cene devraitpas être unterme dans unetaxonomie,vous devriezplutôten faire unepost-méta.Sorry, but you are wrong. Ordering by taxonomy doesn't make any sense in your case either. What do you want to show? All the Breakfasts first, followed by all the Dinners, then all the Lunches? You should select what you want and the order in which you want it, but the taxonomy is just a grouping label. It's not meaningful "data" that you should be ordering by. If it is, then it shouldn't be a term in a taxonomy, you should make it a post-meta instead.
- 2
- 2014-10-20
- Otto
-
Allez,bien sûr,il y aura des cas dans lesquels vous voudrez classer les articlesparterme detaxonomie.Un autreexempleest untype depublication defilm avec unetaxonomie denotation.Dans une liste defilms,ilesttrèsfacile d'imaginer despersonnes souhaitant commander une liste defilmspar classement afin quetous lesfilms classés G,puis PG,etc. apparaissenten haut.(Dans cetexempleet dans l'exemple de repas,ilspourraient être classésparterm_id au lieu denom.) Ilexiste unegrande zonegrise d'instances où vous êtesprobablementmieux servipar unetaxonomieet nonpar uneméta,maisilestprobablement également utile que cettetaxonomie soit order-capable.C'mon, of course there are going to be some instances in which you will want to order posts by taxonomy term. Another example is a Movie post type with a Rating taxonomy. In a list of movies, it's very easy to imagine people wanting to order a list of movies by rating so all G-rated, then PG-rated, etc. movies appear at the top. (In this and the meal example they could be ordered by term_id instead of name.) There's a large gray area of instances where you're probably best served by a taxonomy and not meta, but it's probably also helpful for that taxonomy to be order-able.
- 18
- 2015-03-10
- SeventhSteel
-
Les classements PGet Get autres sont unbon choix detaxonomie,sauf qu'il s'agit de données sur desfilms spécifiques.Ainsi,ils sontméta.Ce sont des données,pas des catégories.Le simplefait d'avoir unnombre limité de choixne faitpas unetaxonomie.S'il abesoin d'untri,alors rendez-leméta ouforcez letripartaxonomie via un code spécifique à lataxonomie.BTW,NC17 vient après PG.Donc,vous avez detoutefaçonbesoin de codepourfaire cette commande.PG and G ratings and such are a good taxonomy choice, except that they are data about specific movies. Thus, they're meta. They're data, not categories. Just having a limited number of choices does not a taxonomy make. If it needs sort by, then either make it meta, or force the sort by the taxonomy via taxonomy specific code. BTW, NC17 comes after PG. So, you need code to do that ordering anyway.
- 2
- 2015-11-10
- Otto
-
Je sais queje suisen retard à lafête avec ce commentaire,maisje suisjustetombé dessus.Le classementpartaxonomiepeut avoir du sens dans certaines situations.Nous avons des offres d'emploi sur unprojeten tant quetype deposte,puis l'Étatet la ville dans lesquels l'emploi setrouve sont destaxonomies.Nous voulons qu'ils soientfacilementgroupables (affichertous lesemplois dans un État ou affichertous lesemplois d'une ville),donc lataxonomie était lameilleure solution.Enmêmetemps,il y a la recherche d'emploigénérale oùnous voulons lestrier d'abordpartitre,puispar état,puispar ville.I know I'm late to the party with this comment, but just bumped into this. Ordering by taxonomy can make sense in some situations. We have job listings on one project as a post type and then State and City in which the job is are taxonomies. We want them to be easily grupable (show all jobs in a state or show all jobs in a city) so taxonomy was the best solution. At the same time there is general job search where we want to sort them first by title, then by state, then by city.
- 0
- 2018-10-23
- Dennis Puzak
-
Un autre cas d'utilisation: un client a untas d'articles,dont chacun a une catégorie.Le client souhaite qu'il y ait unepage répertorianttous les articles,quipeuvent êtretriéspar ordre alphabétique,par date oupar catégorie.Les catégoriespeuvent également êtrefiltrées,mais listertous les articlespar catégoriepar ordre alphabétiquen'estpas sifou d'un cas d'utilisationet vous le voyez apparaître assez souvent.Another use case: A client has a bunch of articles, each of which has a category. The client wants there to be a page listing all the articles, which can be sorted alphabetically, by date, or by category. Categories can also be filtered, but listing all the articles by category alphabetically is not that crazy of a use case and you see it pop up pretty often.
- 0
- 2019-06-06
- Wilson Biggs
-
- 2011-04-08
Oui,mais c'est assez compliqué ...
Ajoutez àfunctions.php dans votrethème:
function orderby_tax_clauses( $clauses, $wp_query ) { global $wpdb; $taxonomies = get_taxonomies(); foreach ($taxonomies as $taxonomy) { if ( isset( $wp_query->query['orderby'] ) && $taxonomy == $wp_query->query['orderby'] ) { $clauses['join'] .=<<<SQL LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) LEFT OUTER JOIN {$wpdb->terms} USING (term_id) SQL; $clauses['where'] .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)"; $clauses['groupby'] = "object_id"; $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) "; $clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC'; } } return $clauses; } add_filter('posts_clauses', 'orderby_tax_clauses', 10, 2 );
Ceciesttiré de certaines chosestrouvéeset de certaines choses quej'aifaitesmoi-même. Expliquerest assez difficile,maisen fin de compte,avec cetteexécution,vouspouvezmettre? Orderby=(taxonomy query var) & amp; order=ASC (ou DESC)et elle décolleratout de suite!
Yes, but it is pretty involved...
Add to functions.php in your theme:
function orderby_tax_clauses( $clauses, $wp_query ) { global $wpdb; $taxonomies = get_taxonomies(); foreach ($taxonomies as $taxonomy) { if ( isset( $wp_query->query['orderby'] ) && $taxonomy == $wp_query->query['orderby'] ) { $clauses['join'] .=<<<SQL LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) LEFT OUTER JOIN {$wpdb->terms} USING (term_id) SQL; $clauses['where'] .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)"; $clauses['groupby'] = "object_id"; $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) "; $clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC'; } } return $clauses; } add_filter('posts_clauses', 'orderby_tax_clauses', 10, 2 );
This is frankensteined from some found stuff and some stuff I did myself. Explaining is pretty tough, but the bottom line is with this running, you may put ?orderby=(taxonomy query var)&order=ASC (or DESC) and she'll take right off!
-
Merci Drew,je vaisessayeret essayer d'exécuter ce SQL,je dois éditer unpeu,mais celapourraitfonctionner.Mon seulproblèmemaintenant,c'est queje vaispeut-être dans lamauvaise direction commeindiquépar Otto.Merci Drew.EDIT - Pasbesoin demodifierje peux voir oùilfautpeaufiner :) MerciThank you Drew, I will give a go and try to run that SQL, need to edit a bit, but it might work. My only problem now, is I might be going on the wrong directions as pointed by Otto. Thank you Drew. EDIT- No need to edit I can see where it needs the tweaking :) Thank you
- 0
- 2011-04-08
- yeope
-
Si vous l'avez saisi dans les deux dernièresminutes,celane fonctionnerapas,allez-yet prenez-lemaintenant,je l'ai réparé.Il a été définipour deuxtaxonomies spécifiques,j'ai amélioré le codepour qu'ilfonctionne surtoutes lestaxonomiesenregistrées.If you grabbed it within the last two minutes, it won't work, go ahead and grab it now, I fixed it. It was set for two specific taxonomies, I improved the code to work on all registered taxonomies.
- 0
- 2011-04-08
- Drew Gourley
-
Merci unefois deplus.Juste au cas oùj'essaierais votre solutionet çamarche.Aussi si quelqu'un d'autre veut l'utiliser,vous devez changer `add_filter ('posts_clauses','orderby_tax_clauses',10,2);`en `add_filter ('posts_clauses','todo_tax_clauses',10,2);` Merci:)thank you once again. Just in case I tried your solution and it kind of works. Also if someone else wants to use it you need to change `add_filter('posts_clauses', 'orderby_tax_clauses', 10, 2 );` to `add_filter('posts_clauses', 'todo_tax_clauses', 10, 2 );` Thank you :)
- 0
- 2011-04-08
- yeope
-
Oui,celaestmaintenant corrigé dans lebloc de code,j'aipris cela d'unprojet sur lequelje travailleet j'ai oublié de changer lenom de lafonctionmême sije l'ai changé dans le hook.Yes, this is now fixed in the code block, I took this from a project I'm working on and forgot to change the name of the function even though I changed it in the hook.
- 0
- 2011-04-09
- Drew Gourley
-
Savez-vous s'ilestpossible de classer lestaxonomiespar ID au lieu dunom?J'essaie d'obtenir lemême résultaten ordonnant lesgroupes detaxonomiepar IDDo you know if it's possible to order the taxonomies by ID instead of the name? I'm trying to get the same result ordering the taxonomy groups by ID
- 1
- 2013-07-16
- Javier Villanueva
-
- 2014-10-31
Créez votre requêtefiscale comme d'habitude.
$tax_query = array(); $tax_query['relation']="OR"; $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $cat_terms, ); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
Configurez vos argumentspour query_posts ou WP_Query
$args = array( 'post_type'=>'post', 'posts_per_page'=>12, 'paged'=>$paged, 'tax_query' => $tax_query, );
Avant d'effectuer votre appel query_posts/WP_Query,connectez-vous aufiltre orderbyet remplacez-le
add_filter('posts_orderby', 'edit_posts_orderby'); function edit_posts_orderby($orderby_statement) { $orderby_statement = " term_taxonomy_id ASC "; return $orderby_statement; } query_posts($args); remove_filter('posts_orderby', 'edit_posts_orderby');
n'oubliezpas de supprimer lefiltrepar la suite ...
celafonctionneb/c latax_query crée lesjointures,etc.pour vous,il vous suffit de classerpar l'un des champs de lajointure.
I'm coming late to the game here, but there is a simpler more WordPressy way of doing this.
Build out your tax query like normal.
$tax_query = array(); $tax_query['relation']="OR"; $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $cat_terms, ); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
Set up your args for query_posts or WP_Query
$args = array( 'post_type'=>'post', 'posts_per_page'=>12, 'paged'=>$paged, 'tax_query' => $tax_query, );
Before you make your query_posts / WP_Query call, hook into the orderby filter and override it
add_filter('posts_orderby', 'edit_posts_orderby'); function edit_posts_orderby($orderby_statement) { $orderby_statement = " term_taxonomy_id ASC "; return $orderby_statement; } query_posts($args); remove_filter('posts_orderby', 'edit_posts_orderby');
don't forget to remove filter afterwards...
this works b/c the tax_query creates the joins etc for you, you just need to order by one of the fields from the join.
-
Uneidée sur lafaçon de classerparnom au lieu determ_taxonomy_id?lamodification determ_taxonomy_id dans orderby_statementgénère deserreursAny idea on how to order by name instead of term_taxonomy_id? changing term_taxonomy_id in orderby_statement throws errors
- 2
- 2016-10-04
- tehlivi
-
C'est labonne réponsepour quiconqueestintéressé!This is the correct answer for anyone that is interested!
- 4
- 2018-06-21
- Mayra M
-
- 2017-07-06
Jene saispaspourquoitoutes les solutionsici le surpassent.OK,il y a une demi-décennie,maisj'exécutejuste le code suivant actuellementet celafonctionne:
<?php // Default $wheels_args = array( 'post_type' => 'wheels', 'posts_per_page' => '96', 'orderby' => 'taxonomy, name', // Just enter 2 parameters here, seprated by comma 'order'=>'ASC' ); $loop = new WP_Query($wheels_args); ?>
Celatriera lestaxonomies de votre CPT d'abordpar sataxonomiepar ordre alphabétiqueet au sein de cesgroupes detaxonomie égalementpar ordre alphabétique.
I'm not sure why all solutions here are pretty much overkilling it. OK, it's half a decade ago, but I'm just running the following code currently and it works:
<?php // Default $wheels_args = array( 'post_type' => 'wheels', 'posts_per_page' => '96', 'orderby' => 'taxonomy, name', // Just enter 2 parameters here, seprated by comma 'order'=>'ASC' ); $loop = new WP_Query($wheels_args); ?>
This will sort the taxonomies of your CPT first by it's taxonomy in alphabetical order and within these taxonomy groups als by alphabetical order.
-
@yeope Pourquoiest-ce la réponse acceptée !?Dieumerci,j'aifait défiler@yeope Why is this the accepted answer!? thank god I scrolled
- 0
- 2019-10-21
- Juan Solano
-
nepouvaitpasfairefonctionner cela.pouvez-vouspointer vers un site avec quelquesexplications à ce sujet?[rienici,] (https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) qui sauvegarde votre codecouldn't get this to work. can you point to a site with some explanation to that? [nothing here,](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) that backs your code up
- 1
- 2020-04-09
- honk31
-
- 2015-01-04
Ehbien,j'aimeraisexposermonexpérience dans letri destypes d'articlespersonnaliséspar catégorie/taxonomie.
LE WEB
- Un site Web d'agence de voyagesfonctionnant sur WordPress
- Contenuprincipal dutype demessagepersonnalisé appelé "ruta"
- Taxonomie avec cette structure Type-of-travel> continent> country
LE CAS
Dans lespages de liste des catégories d'archives,le client voulait que les articles soienttriéspar
- Le continent,triéparnombre d'itinéraires sur chacun d'eux.
- Lepays,par ordre alphabétique.
LES ÉTAPES
Tout d'abord ,j'attrape la requête de la requête depage d'archivenonmodifiée qui setrouvait être comme ceci:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,25,26,28,29,31,32,33,35,38,95,101,102,193) ) AND wp_posts.post_type IN ('ruta', 'nav_menu_item') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 45 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 20
Deuxièmement ,j'aimodifié le code sql de Sequel Propar rapport à labase de donnéespour répondre àmesbesoins. Je sors avec ça (oui,çapeutprobablement être amélioré:mon les connaissances sur MySQLne sontpasexceptionnelles):
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID, tt1.parent AS pare, ( SELECT COUNT(*) FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_term_taxonomy AS tt2 ON ( tt2.term_taxonomy_id = tt1.term_taxonomy_id ) WHERE 1=1 AND tt1.parent = pare ) AS Total FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_terms ON ( tt1.term_id = wp_terms.term_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,25,26,28,29,31,32,33,35,38,95,101,102,193) ) AND wp_posts.post_type IN ('ruta', 'nav_menu_item') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 45 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY total DESC, wp_terms.name
Troisièmement ,j'ai accroché la requête sur lefichierfunctions.php avectroisfiltres:posts_fields,posts_joinet posts_orderby
Le code dansfunctions.php:
function xc_query_fields( $fields ) { $fields = "wp_posts.ID, wp_posts.post_title, wp_terms.name, tt1.parent AS pare, ( SELECT COUNT(*) FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_term_taxonomy AS tt2 ON ( tt2.term_taxonomy_id = tt1.term_taxonomy_id ) WHERE 1=1 AND tt1.parent = pare ) AS Total"; return $fields; } function xc_query_joins( $join ) { $join .= "INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_terms ON ( tt1.term_id = wp_terms.term_id )"; return $join; } function xc_query_orderby( $join ) { $join = "total DESC, wp_terms.name "; return $join; }
Enfin j'ai déclenché lesfiltres àpartir du hookpre_get_post selon certaines conditions
function filtra_queries( $query ) { if ( is_archive() && $query->is_main_query() && !is_admin() ) { $rutes = array('viajes-privados', 'asia', 'africa', 'oceania', 'america', 'oriente-proximo'); if ( in_array( $query->get('category_name'), $rutes ) ) { add_filter( 'posts_fields', 'xc_query_fields' ); add_filter( 'posts_join', 'xc_query_joins' ); add_filter( 'posts_orderby', 'xc_query_orderby' ); }// end if in_array }// end if is_archive } add_filter('pre_get_posts', 'filtra_queries');
J'espère que celapeut aider quelqu'un
Well, I’d like to expose my experience in sorting custom post types by category/taxonomy.
THE WEB
- A travel agency web site running on WordPress
- Main content on custom post type called ‘ruta’
- Taxonomy with this structure Type-of-travel > continent >country
THE CASE
In archive category list pages, the client wanted the posts to be sorted by
- The continent, ordered by number of routes on each one.
- The country, ordered alphabetically.
THE STEPS
First, I catch the request from the unmodified archive page query which happened to be like this:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,25,26,28,29,31,32,33,35,38,95,101,102,193) ) AND wp_posts.post_type IN ('ruta', 'nav_menu_item') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 45 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 20
Second, I edited the sql code in Sequel Pro against the database to conform my needs. I come out with this (yes, probably it can be improved: my knowledge on MySQL is not outstanding):
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID, tt1.parent AS pare, ( SELECT COUNT(*) FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_term_taxonomy AS tt2 ON ( tt2.term_taxonomy_id = tt1.term_taxonomy_id ) WHERE 1=1 AND tt1.parent = pare ) AS Total FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_terms ON ( tt1.term_id = wp_terms.term_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,25,26,28,29,31,32,33,35,38,95,101,102,193) ) AND wp_posts.post_type IN ('ruta', 'nav_menu_item') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 45 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY total DESC, wp_terms.name
Third, I hooked the query on the functions.php file with three filters: posts_fields, posts_join and posts_orderby
The code in functions.php:
function xc_query_fields( $fields ) { $fields = "wp_posts.ID, wp_posts.post_title, wp_terms.name, tt1.parent AS pare, ( SELECT COUNT(*) FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_term_taxonomy AS tt2 ON ( tt2.term_taxonomy_id = tt1.term_taxonomy_id ) WHERE 1=1 AND tt1.parent = pare ) AS Total"; return $fields; } function xc_query_joins( $join ) { $join .= "INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy AS tt1 ON ( tt1.term_taxonomy_id = wp_term_relationships.term_taxonomy_id ) INNER JOIN wp_terms ON ( tt1.term_id = wp_terms.term_id )"; return $join; } function xc_query_orderby( $join ) { $join = "total DESC, wp_terms.name "; return $join; }
Finally I triggered the filters from the pre_get_post hook according to some conditions
function filtra_queries( $query ) { if ( is_archive() && $query->is_main_query() && !is_admin() ) { $rutes = array('viajes-privados', 'asia', 'africa', 'oceania', 'america', 'oriente-proximo'); if ( in_array( $query->get('category_name'), $rutes ) ) { add_filter( 'posts_fields', 'xc_query_fields' ); add_filter( 'posts_join', 'xc_query_joins' ); add_filter( 'posts_orderby', 'xc_query_orderby' ); }// end if in_array }// end if is_archive } add_filter('pre_get_posts', 'filtra_queries');
Hope this can help somebody
-
Beautravail,ridicule qu'on aitpris cette quantité de codepourtrier quelque chosepar unetaxonomie.Énormeproblème avec WP.Nice work, ridiculous that is took this quantity of code to sort something by a taxonomy. Huge problem with WP.
- 0
- 2017-07-20
- serraosays
-
- 2017-04-10
J'aieu unproblèmetrès similaire auquelj'ai été confronté:je veux commander une archive detype articlepersonnalisée (articles demagazine)par unetaxonomiepersonnalisée (numéros). Jene faisjamais de requêtes SQL directes surmon site -et généralement si vous êtes comme ces autres réponses - vous devez repenser votre approche.
PROBLÈMES:
1) Wordpressne vouspermetpas de classer lestaxonomies demanièreintelligente.
2) Wordpressn'autorisetout simplementpas
orderby
à utiliser destaxonomies sur WP_Querypost-type (commeindiquépar Otto).SOLUTIONS:
1) Letri destaxonomiesestmieux réalisépar Plugin de commande detaxonomiepersonnalisée NE pour lemoment. Il vouspermet de commander lataxonomie via WYSIWYG dans
wp-admin
ce quin'estpas comme ça queje leferaismaisje n'ai rientrouvé demieux.Lorsque vous configurez leplugin,vous obtenez quelque chose de similaire à ce quej'aifaitici. Notez l'option
Auto-sort Queries of this Taxonomy
- définissez-la surCustom Order as Defined Above
; cela vous donne la commande dont vous avezbesoin. Capture d'écran:2) Avec unetaxonomietriéeen place,vouspouvezmaintenant créer une série d'appels WP_Query quiparcourent chaqueterme,créant ainsi une archive ordonnéepar lataxonomie. Utilisez
get_terms()
pour créer untableau detous lestermesfiscaux,puisexécutez unforeach
sur chaqueterme. Cela crée unWP_Query
pour chaque élément determe qui renverratoutes lespublicationspour unterme donné,créant ainsi une archivetriéeparterme detaxonomie. Codepour yparvenir:// Get your terms and put them into an array $issue_terms = get_terms([ 'taxonomy' => 'issues', 'hide_empty' => false, ]); // Run foreach over each term to setup query and display for posts foreach ($issue_terms as $issue_term) { $the_query = new WP_Query( array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'issues', 'field' => 'slug', 'terms' => array( $issue_term->slug ), 'operator' => 'IN' ) ) ) ); // Run loop over each query while($the_query->have_posts()) : $the_query->the_post(); // YOUR TEMPLATE OUTPUT FOR EACH POST endwhile; }
Lecture connexe sur ce site: Affichertous lesmessages dans untype demessagepersonnalisé,regroupépar unetaxonomiepersonnalisée
I had a very similar problem that I dealt with: I want to order a custom post-type archive (magazine articles) by a custom taxonomy (issues). I never do direct SQL queries on my site - and usually if you are like these other answers - you need to rethink your approach.
PROBLEMS:
1) Wordpress doesn't allow you to order taxonomies in any intelligent way.
2) Wordpress just doesn't allow
orderby
to be use taxonomies on post-type WP_Query (as spelled out by Otto).SOLUTIONS:
1) Sorting taxonomies is best accomplished by the Custom Taxonomy Order NE plugin at the moment. It allows you to order the taxonomy via WYSIWYG in
wp-admin
which isn't how I would do it but I haven't found anything better.When you setup the plugin, you'll get something similar to what I've done here. Make note of the option
Auto-sort Queries of this Taxonomy
- set this toCustom Order as Defined Above
; this gets you the ordering you need. Screenshot:2) With a sorted taxonomy in place, you can now create a series of WP_Query calls that run through each term, effectively creating an archive ordered by the taxonomy. Use
get_terms()
to create an array of all tax terms, then run aforeach
over each term. This creates aWP_Query
for each term item that will return all posts for a given term, effectively creating an archive ordered by taxonomy term. Code to make this happen:// Get your terms and put them into an array $issue_terms = get_terms([ 'taxonomy' => 'issues', 'hide_empty' => false, ]); // Run foreach over each term to setup query and display for posts foreach ($issue_terms as $issue_term) { $the_query = new WP_Query( array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'issues', 'field' => 'slug', 'terms' => array( $issue_term->slug ), 'operator' => 'IN' ) ) ) ); // Run loop over each query while($the_query->have_posts()) : $the_query->the_post(); // YOUR TEMPLATE OUTPUT FOR EACH POST endwhile; }
Related reading on this site: Display all posts in a custom post type, grouped by a custom taxonomy
-
- 2017-03-24
Voici la solution quej'ai utiliséepour ceproblèmeparticulier. Cette solutionestpour les casextrêmes oùiln'estpaspossible à lafois d'utiliser unfiltre
pre_get_posts
et ilexiste unepagination sur la requête (ex: WooCommerce):global $wpdb; $taxonomies = array('my-tax-1', 'my-tax-2', 'my-tax-3'); $orderby = "'".implode("', '", array_keys($taxonomies))."'"; $id_sql = $GLOBALS['wp_query']->request; $id_sql = preg_replace('/LIMIT\s+\d+\s?,?\s\d*/', '', $id_sql); $id_sql = str_replace('SQL_CALC_FOUND_ROWS', '', $id_sql); $term_sql = "SELECT tt.taxonomy AS `taxonomy`, t.name AS `term_name`, t.slug AS `term_slug`, count(*) AS `term_count` FROM ({$id_sql}) p JOIN wp_term_relationships tr ON p.ID = tr.object_id JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN wp_terms t ON tt.term_id = t.term_id WHERE tt.taxonomy IN ({$orderby}) GROUP BY t.slug ORDER BY FIELD(tt.taxonomy, {$orderby})"; // Add further specific ordering here $results = $wpdb->get_results($term_sql, ARRAY_A);
J'ai utilisé cecipour créer unmenu denavigationtriépartaxonomie,termeet nombre depublicationsparterme.
Si vous voulez simplement lesmessages,changez la requêteen
SELECT p.*
etGROUP BY p.ID
Here's the solution I've used for this particular problem. This solution is for extreme cases where it is both not possible to use a
pre_get_posts
filter and there is existing pagination on the query (ie: WooCommerce):global $wpdb; $taxonomies = array('my-tax-1', 'my-tax-2', 'my-tax-3'); $orderby = "'".implode("', '", array_keys($taxonomies))."'"; $id_sql = $GLOBALS['wp_query']->request; $id_sql = preg_replace('/LIMIT\s+\d+\s?,?\s\d*/', '', $id_sql); $id_sql = str_replace('SQL_CALC_FOUND_ROWS', '', $id_sql); $term_sql = "SELECT tt.taxonomy AS `taxonomy`, t.name AS `term_name`, t.slug AS `term_slug`, count(*) AS `term_count` FROM ({$id_sql}) p JOIN wp_term_relationships tr ON p.ID = tr.object_id JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN wp_terms t ON tt.term_id = t.term_id WHERE tt.taxonomy IN ({$orderby}) GROUP BY t.slug ORDER BY FIELD(tt.taxonomy, {$orderby})"; // Add further specific ordering here $results = $wpdb->get_results($term_sql, ARRAY_A);
I've used this to create a nav menu ordered by taxonomy, term, and count of posts-per-term.
If you simply want the posts then change the query to
SELECT p.*
andGROUP BY p.ID
-
- 2017-04-22
C'est comme une requête avant la requête,mais celane dérangerapas sinousne demandonspastrop demessages ... L'idéeest demodifier la requêteprincipale afin quenousn'ayonsmêmepasbesoin d'accéder auxmodèleset degénérernouvelles requêteset boucles ...
function grouped_by_taxonomy_main_query( $query ) { if ( $query->is_home() && $query->is_main_query() ) { // Run only on the homepage $post_ids = array(); $terms = get_terms('my_custom_taxonomy'); foreach ( $terms as $term ) { $post_ids = array_merge( $post_ids, get_posts( array( 'posts_per_page' => 4, // as you wish... 'post_type' => 'my_custom_post_type', // If needed... Default is posts 'fields' => 'ids', // we only want the ids to use later in 'post__in' 'tax_query' => array( array( 'taxonomy' => $term->taxonomy, 'field' => 'term_id', 'terms' => $term->term_id, )))) // getting posts in the current term ); } $query->query_vars['post_type'] = 'my_custom_post_type'; // Again, if needed... Default is posts $query->query_vars['posts_per_page'] = 16; // If needed... $query->query_vars['post__in'] = $post_ids; // Filtering with the post ids we've obtained above $query->query_vars['orderby'] = 'post__in'; // Here we keep the order we generated in the terms loop $query->query_vars['ignore_sticky_posts'] = 1; // If you dont want your sticky posts to change the order } } // Hook my above function to the pre_get_posts action add_action( 'pre_get_posts', 'grouped_by_taxonomy_main_query' );
It's like a query before the query, but won't bother if we're not not querying too many posts... The idea is to modify the main query so we don't even need to go to templates and generate new queries and loops...
function grouped_by_taxonomy_main_query( $query ) { if ( $query->is_home() && $query->is_main_query() ) { // Run only on the homepage $post_ids = array(); $terms = get_terms('my_custom_taxonomy'); foreach ( $terms as $term ) { $post_ids = array_merge( $post_ids, get_posts( array( 'posts_per_page' => 4, // as you wish... 'post_type' => 'my_custom_post_type', // If needed... Default is posts 'fields' => 'ids', // we only want the ids to use later in 'post__in' 'tax_query' => array( array( 'taxonomy' => $term->taxonomy, 'field' => 'term_id', 'terms' => $term->term_id, )))) // getting posts in the current term ); } $query->query_vars['post_type'] = 'my_custom_post_type'; // Again, if needed... Default is posts $query->query_vars['posts_per_page'] = 16; // If needed... $query->query_vars['post__in'] = $post_ids; // Filtering with the post ids we've obtained above $query->query_vars['orderby'] = 'post__in'; // Here we keep the order we generated in the terms loop $query->query_vars['ignore_sticky_posts'] = 1; // If you dont want your sticky posts to change the order } } // Hook my above function to the pre_get_posts action add_action( 'pre_get_posts', 'grouped_by_taxonomy_main_query' );
-
- 2020-04-09
J'aimetriermestermesmanuellement,doncj'utilise unpluginpour lefaire.et je suisfan dufiltre
pre_get_posts
,j'ai doncpris l'exemple de Drew Gourleyet je l'aifaitfonctionner avec ça. donc c'est un cas unpeu spécial,maisje poste quandmême ça,au cas où ça aiderait quelqu'un. le code suivant va dansfunctions.php ou dans unpluginpersonnalisé.commençonspar lefiltre.nous commandons letype demessagepersonnalisé
music
partaxonomiepersonnaliséestyle
function so14306_pre_get_posts($query) { if (is_admin()) : return; endif; if ($query->is_main_query()) : if (is_post_type_archive('music')) : $query->set('orderby', 'style'); endif; endif; } add_action('pre_get_posts', 'so14306_pre_get_posts');
puisnous appelons lefiltrepost_clauses:
function so14306_posts_clauses($clauses, $wp_query) { global $wpdb; if (isset($wp_query->query_vars['orderby']) && $wp_query->query_vars['orderby'] === 'style') { $orderby = $wp_query->query_vars['orderby']; $clauses['join'] .= <<<SQL LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) LEFT OUTER JOIN {$wpdb->terms} USING (term_id) SQL; $clauses['where'] .= " AND (taxonomy = '{$orderby}' OR taxonomy IS NULL)"; $clauses['groupby'] = "object_id"; $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.term_order ORDER BY {$wpdb->terms}.term_order ASC) ASC"; $clauses['orderby'] .= ", {$wpdb->posts}.post_name ASC"; } return $clauses; } add_filter('posts_clauses', 'so14306_posts_clauses', 10, 2);
ilne vous resteplus qu'àtrier vostaxonomies avec leplugin suivant: Commande depostepersonnalisée simple . Ce pluginest obligatoire pour cette solution,caril ajoute la colonne
term_order
à labase de données!et cette ligneici:
$clauses['orderby'] .= ", {$wpdb->posts}.post_name ASC"
trie les articlespartitre,donc letri complet de la solution ci-dessusest:taxonomyterm=>titre dumessage.i like to sort my terms manually, so i use a plugin to do so. and i'm a fan of the
pre_get_posts
filter, so i took the proper working example of Drew Gourley and made it work with that. so this is some kinda special case, but i'm posting this anyhow, in case it helps someone. following code goes into functions.php or a custom plugin.first lets start of with the filter. we order the custom post type
music
by custom taxonomystyle
function so14306_pre_get_posts($query) { if (is_admin()) : return; endif; if ($query->is_main_query()) : if (is_post_type_archive('music')) : $query->set('orderby', 'style'); endif; endif; } add_action('pre_get_posts', 'so14306_pre_get_posts');
then we call the post_clauses filter:
function so14306_posts_clauses($clauses, $wp_query) { global $wpdb; if (isset($wp_query->query_vars['orderby']) && $wp_query->query_vars['orderby'] === 'style') { $orderby = $wp_query->query_vars['orderby']; $clauses['join'] .= <<<SQL LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) LEFT OUTER JOIN {$wpdb->terms} USING (term_id) SQL; $clauses['where'] .= " AND (taxonomy = '{$orderby}' OR taxonomy IS NULL)"; $clauses['groupby'] = "object_id"; $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.term_order ORDER BY {$wpdb->terms}.term_order ASC) ASC"; $clauses['orderby'] .= ", {$wpdb->posts}.post_name ASC"; } return $clauses; } add_filter('posts_clauses', 'so14306_posts_clauses', 10, 2);
now all you need to do, is sort your taxonomies with the following plugin: Simple Custom Post Order. This plugin is mandatory for this solution, since it adds the column
term_order
to the database!and this line here:
$clauses['orderby'] .= ", {$wpdb->posts}.post_name ASC"
orders the posts by title, so the full sorting of the above solution is: taxonomy term => post title.
Ma questionest simple,j'utilise
WP_Query
pour récupérer desmessages detypepersonnaliséfiltréspar unetaxonomieen utilisanttax_query
.Maintenant,monproblèmeest queje voudrais
orderby
lataxonomy
,mais àpartir de la documentationet de la recherche sur le Web,je netrouvepas de solution.Le
orderby
dansWP_Query
vouspermet de classer selon untas de champsmême desméta-champspersonnalisés,maisilne semblepasprendreen charge lataxonomie.Despointeurs dans labonne direction?
Merci àtous.