Utilizzando wp_query è possibile ordinare per tassonomia?
10 risposta
- voti
-
- 2011-04-08
No,non èpossibile ordinarepertassonomia,perché da un certotipo dipunto di vista,in realtànon hamolto senso.
Letassonomie sonomodiper raggruppare le coseinsieme. Quindiilpunto di avere unatassonomia suipost sarebbe davvero avereterminiin quellatassonomia condivisitrai post. Se unatassonomia avessetermini che sono stati usati solo su unpost ciascuno,allora latassonomia sarebbeinutile. E sei terminifossero condivisi come dovrebberoessere,ordinarliin base a questinonprodurrebbenulla diparticolarmente utile.
Quello che dovresti usarein una situazione delgenere èilmetapost. Puoi ordinarepermetaposted è unicoper ognipost.
Modifica: Detto questo,puoi ordinarein base allatassonomia creando una query SQLpersonalizzata utilizzando unfiltro,semplicementenonpuoifarlo da un WP_Querynonmodificato: http://scribu.net/wordpress/sortable-taxonomy-columns.html
Tuttavia,se devi ricorrere a questogenere di cose,la struttura diprogettazione dei dati è sbagliatain primo luogo. I "termini"nellatassonomianon sono "dati"effettivi. Itermini stessinon hanno alcun significatointrinseco,sono soloetichetteperilparticolare raggruppamento che stanno descrivendo. Se litratti come dati significativi,allora hai un difetto diprogettazione sottostante.
Letassonomie raggruppano le cose assegnando loro deitermini. Quel raggruppamento èilpunto centrale delletassonomie,i termini sono solo deibei voltinel raggruppamento. Se haimetadati significativi da assegnare a unpost,dovrestiinvece utilizzareilmetapost. E che puoi ordinare,perchépostmeta utilizza sia chiavi che valoripermemorizzare leinformazioni. Con unatassonomia,in realtàmemorizzi solo le chiavi,i cui valori sonoi post raggruppatiin base a queltermine.
Le cose sonopiùfacili a lungotermine se usi l'approccio correttoper questo. Anche senon sto dicendo chenonpuoifare qualcosa di strano con latassonomia,stai solo rendendo le cosepiù difficiliperte stesso a lungotermine usandolain modo sbagliato.
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.
-
Ciao Otto,grazieper la risposta.Capiscoiltuopuntoe forse sto andandonella direzione sbagliata con questo.Nelmioesempio un sito diprogrammitelevisivi,hotassonomiaper serie 1,serie 2,serie 3ecc. Quindiposso raggrupparetuttii diversiprogrammitelevisivipernumero di serie.Poi ho lo stessopergliepisodi,Episodio 01,Episodio 02,ecc. Quello che vorrei è quandomostro unelenco dituttigliepisodiin ordineperepisodioe serie.Analizzerò quindiposteròmetae campipersonalizzati.Grazie 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 latuatassonomia dovrebbeessere seriee ituoitermini dovrebberoessere serie 1,serie 2ecc. Congliepisodipresumo che una serie contengapiùepisodi,quindipotrebbe usare la stessatassonomia,"serie"e se sonogerarchici,l'episodio 1,l'episodio 2ecc. avrebbeilterminegenitore "serie x".Quindipotrestiinterrogare un'intera seriein ordine congliepisodi che cadonoin linea dove dovrebbero.@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 vedo,potrestiessere coni soldi lì!L'unicoproblema cheposso vedere èilfatto di dover ripeterei termini "Episodio 1","Episodio 2"per ogni serie.Inoltre,nonesserein grado di raggrupparetuttigliepisodi 1non dipende dalla serie,mapenso cheprobabilmente ci sia unmodoper aggirarlo.Grazie 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
-
Usare unatassonomiapergliepisodinon hamolto senso,in realtà,perchéil raggruppamento èinutile.Pensaci,se hai "episodio 1" cometermine,allora stai raggruppando l'episodio 1 con ogni altroepisodio 1 di ogni altroprogramma TV.Inumeri dell'episodioe della serie hannopiù senso comepost_meta,perché sono specificiper quelparticolare spettacoloe non sono utili comegruppo.Ilnome delprogrammatelevisivo sarebbe utile cometerminein unatassonomia diprogrammitelevisivi,perché quindi stai raggruppando lo spettacolonel suoinsieme.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
-
Ma unatassonomiaper le serie _kinda_funziona,ma soloperché raggruppagli spettacoliin una stagione o qualcosa delgenere,anche se dovrestiinterrogarla anche con latassonomia deiprogrammitelevisivi.In unataletassonomia di serie,i tuoitermini sarebbero 1,2,3,che rappresentanoilnumero della stagionein cui sitrovava lo spettacolo. Ma vorresti comunque questeinformazioni comepostmeta dipiù,dato che vuoi ordinarlein base aesse.Epoichépuoieseguire query anche supostmeta,non ha alcun senso duplicarlo cometassonomia.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,allafine sono andato coni campipersonalizzati :) Avevapiù senso.@Otto, in the end I went with custom fields :) It made more sense.
- 0
- 2011-05-04
- yeope
-
Otto hafatto seguito a questo con uninteressantepost sulblog: [Quando (non) usare unatassonomiapersonalizzata] (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 Grazieper aver condiviso questo,è davverobello leggere unpo 'dipiù sulletassonomiee sui loro usi.Inparticolare,mi interessa conoscerei tuoipensieri su una situazione come quella descrittanelpost [Sortable Taxonomy Columns] (http://scribu.net/wordpress/sortable-taxonomy-columns.html).Quale sarebbe la soluzionemigliore quando voglio cheentrambi sianoin grado diinterrogaretuttii postin unagamma di colori,ma voglio anche ordinareper colore?Forse questa sarebbe lamigliore domanda aparte ...@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
-
Se vuoi ordinarein base aesso,allora dovrebbeessere davverometainvece di unatassonomia.L'ordinamentopertassonomianon hamolto senso,realisticamente.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
-
Grazie @Otto.Anche senon sono d'accordo con latua affermazione: "Tuttavia,se devi ricorrere a questogenere di cose,latua struttura diprogettazione dei dati è sbagliatain primo luogo." ... Potrebbeessere utile ricorrere alelenco deipostpertermine di categoria sul lato amministratore ...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 Questonon hamolto senso.Ipostpossono averepiù categorie.Per cosa stai classificando?Qual èiltuo criterio di ordinamento secondario quando duepost hanno la stessa categoria?Questo èiltipo diproblemain cuiti imbatti,letassonomie sono solo raggruppamenti,il "termine" è solo unbel visoin quel raggruppamento,non è laparteimportante.Laparteimportante èilgruppo stesso.Non si ordinano alfabeticamentei nomi degli animaliin base alla lorotassonomia linneana.Nonti aiutaperniente.@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
-
Ciao @Otto,hai ragione.Hopreso come riferimentoil caso delmioprogetto attuale che è abbastanzaparticolare ... Un CPT (film) che consente solo un singolotermine ditaxonmypersonalizzato (festival) conpulsanti di opzioneper la sua selezione.L'ordinepredefinito della lista CPT èpertermine (festival) chein questo casoparticolare è abbastanza logico,no?Non riesco apensare a un approcciomigliore al "data design" ... Hoimplementato "festival" cometassonomiaperchégli unici dati di cui hannobisogno sono la loro descrizionee raggruppa logicamentei "film". PS: scusaperilmioinglese.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
-
Sì,abbastanzagiusto,ma allora è ungruppo.Stai raggruppando le coseinsieme.Cosa significa "ordinaper"in un simile contesto?Se haimolte cosenello stessogruppo,puoi "selezionareper" quelgruppo,e questo ha senso,ma "ordinare" è qualcosa di completamente diverso.Ordinateper campi che hanno valori diversi,nonper campi che hannotuttigli stessi valori.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
-
Scusa @Otto,noto solo ora latua risposta ... Sonototalmente d'accordo coni tuoipunti semanticie latua logica.Manelmio contesto,"ordinareper" sarebbeprincipalmente una questione **ergonomica **.** Raggruppare visivamente ** leproiezioniper "festival"può aiutarein modo abbastanzaimportante l'utente a ottenere un curriculum visivobasato sulfattorepiùimportanteper lui,questo a colpo d'occhio.Quindi,non sono sicuro dipoter ottenere questoin un altromodo che con "smistamento" che sono d'accordonon è untermine appropriato ...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 risposta accettataper questa domanda èinaccettabile. Èillogicopresumere che l'ordinamentofiscale "non abbia senso". La risposta che ha datonon ha senso.
Considera l'idea di avere untipo dimessaggio dimenu. Quindi hai unatassa doganale di "FoodCategories". Latassa FoodCategoriesprevedetermini "Colazione","Pranzo"e "Cena". Seinvii una query utilizzandoilparametrotax_query,ora hai un set di risultati contuttii termini,tuttavia sono ordinatiper data dipubblicazione.
Per ottenere l'ordine corretto da questi,in relazione ai lorotermini,e quindi visualizzare sulfront-endin modo appropriato separandoi postnelle loro varie categorie,devi scorrereil set di risultati,quindiinterrogare ogniindividuopubblicare all'interno del set di risultatipertrovarei terminie confrontarli coniltermine corrente,filtrarein un arraye continuarepertutto. Quindi devi dinuovo scorrereilnuovo arrayper la visualizzazione. Questonon èproduttivo.
Sarebbebello se WP avesse un'opzione orderby "tax__in" comefa una "post__in",mapoichénon lofa,devieseguireil ridicoloprocesso di cui sopra;personalizzatu stesso la querytramiteilfiltro "posts_orderby"e "posts_join"permodificareilmetodo orderbye aggiungereiltermine al set di risultati,rispettivamente; oppure devifare unanuova queryper ognitermine che staifiltrando all'interno delle sezioni html relative a queitermini.
La soluzionepiùefficiente sarebbemodificare la stringa di querytramitefiltri. Ilmodopiù semplice sarebbeeseguiretre query separate. L'API WP dovrebbegestiregli ordiniin base alletasse o qualsiasiparametro di query restrittivo. Se stai limitando una queryin base a determinate condizioni,c'è un'altaprobabilità chemolti avrannobisogno di ordinarein base a quelle stesse condizioni.
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.
-
Scusa,mati sbagli.Ordinarein base allatassonomianon ha alcun sensoneancheneltuo caso.Cosa vuoimostrare?Primatutte le colazioni,poitutte le cene,poituttii pranzi?Dovresti selezionare ciò che desiderie l'ordinein cui lo desideri,ma latassonomia è solo un'etichetta di raggruppamento.Non sono "dati" significativiin base ai quali dovresti ordinare.Se lo è,non dovrebbeessere unterminein unatassonomia,dovrestiinvece renderlo unpost-meta.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
-
Dai,ovviamente ci saranno alcuni casiin cui vorrai ordinarei postin base altermine dellatassonomia.Un altroesempio è untipo dipost difilm con unatassonomia di valutazione.In unelenco difilm,èmoltofacileimmaginare che lepersone vogliano ordinare unelenco difilmin base alla valutazionein modo chetuttii film classificati G,poi classificati PG,ecc. Appaianoin alto.(In questoe nell'esempio delpastopotrebberoessere ordinatiperterm_id anzichépernome.) C'è una vasta areagrigia di casiin cuiprobabilmente seimeglio servito da unatassonomiae non da unameta,maprobabilmente è anche utile che quellatassonomia sia ordinata-able.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
-
Le classificazioni PGe Ge simili sono unabuona scelta ditassonomia,tranneperilfatto che sono dati sufilm specifici.Quindi,sonometa.Sono dati,non categorie.Solo avere unnumero limitato di sceltenonfa unatassonomia.Se habisogno di un ordinamento,rendilometa oforza l'ordinamentoin base allatassonomiatramiteil codice specifico dellatassonomia.BTW,NC17 viene dopo PG.Quindi,hai comunquebisogno del codicepereseguire l'ordine.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
-
So diesserein ritardo allafesta con questo commento,mami sonoimbattutoin questo.Ordinarein base allatassonomiapuò avere sensoin alcune situazioni.Abbiamo annunci di lavoro su unprogetto cometipo diposte poi Statoe Cittàin cui sitrovail lavoro sonotassonomie.Vogliamo che sianofacilmente raggruppabili (mostratuttii lavoriin uno stato omostratuttii lavoriin una città),quindi latassonomiaera la soluzionemigliore.Allo stessotempo c'è una ricercagenerale di lavoroin cui vogliamo ordinarliprimapertitolo,poiper stato,poiper città.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 altro caso d'uso: un client ha una serie di articoli,ognuno dei quali ha una categoria.Il cliente vuole che ci sia unapagina cheelenchituttigli articoli,chepossonoessere ordinati alfabeticamente,per data oper categoria.Le categoriepossono ancheesserefiltrate,maelencaretuttigli articoliper categoriain ordine alfabeticonon è un caso d'usofollee lo vedi apparire abbastanza spesso.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
Sì,ma èpiuttosto complicato ...
Aggiungi afunctions.phpneltuotema:
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 );
Questo èfranco da alcune cosetrovatee da cose che hofattoio stesso. Spiegare èpiuttosto difficile,ma la conclusione è che con questofunzionamento,puoimettere? Orderby=(query ditassonomia var) & amp; order=ASC (o DESC)e lei sene andrà subito!
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!
-
Grazie Drew,proverò aeseguire quell'SQL,hobisogno dimodificare unpo ',mapotrebbefunzionare.Ilmio unicoproblema ora è chepotrei andarenella direzione sbagliata,comeindicato da Otto.Grazie Drew.EDIT- Non c'èbisogno dimodificare,posso vedere dove habisogno di ritocchi :) GrazieThank 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
-
Se l'hai afferratonegli ultimi dueminuti,nonfunzionerà,vai avantie prendilo ora,l'ho riparato.Eraimpostatoper duetassonomie specifiche,homiglioratoil codiceper lavorare sututte letassonomie registrate.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
-
grazie ancora.Nel caso avessiprovato latua soluzionee funzionasse.Inoltre,se qualcun altro vuole usarlo,devi cambiare `add_filter ('posts_clauses','orderby_tax_clauses',10,2);`in `add_filter ('posts_clauses','todo_tax_clauses',10,2);` Grazie:)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
-
Sì,ora è stato risoltonelblocco di codice,l'hopreso da unprogetto a cui sto lavorandoe ho dimenticato di cambiareilnome dellafunzione anche se l'ho cambiatonell'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
-
Sai se èpossibile ordinare letassonomieper IDinvece chepernome?Sto cercando di ottenere lo stesso risultato ordinandoi gruppi ditassonomiaper 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
Arrivotardi algioco qui,maesiste unmodopiù semplicee WordPressyperfarlo.
Crea latua queryfiscale come al solito.
$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;
Impostai tuoi argomentiper query_posts o WP_Query
$args = array( 'post_type'=>'post', 'posts_per_page'=>12, 'paged'=>$paged, 'tax_query' => $tax_query, );
Prima dieffettuare la chiamata query_posts/WP_Query,agganciati alfiltro orderbye sovrascriverlo
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');
non dimenticare di rimuovereilfiltroin seguito ...
questofunzionab/ctax_query creai joinecc.perte,devi solo ordinarein base a uno dei campi daljoin.
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.
-
Qualcheidea su come ordinarepernomeinvece diterm_taxonomy_id?lamodifica diterm_taxonomy_idin orderby_statementgeneraerroriAny 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
-
Questa è la risposta correttaper chiunque siainteressato!This is the correct answer for anyone that is interested!
- 4
- 2018-06-21
- Mayra M
-
- 2017-07-06
Non sono sicuro delmotivoper cuitutte le soluzioni qui lo stianoesagerando.OK,èmezzo decenniofa,ma attualmente sto soloeseguendoil seguente codicee funziona:
<?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); ?>
Questo ordinerà letassonomie deltuo CPTprimain base alla suatassonomiain ordine alfabeticoe all'interno di questigruppi ditassonomia anchein ordine alfabetico.
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 Perché questa è la risposta accettata !?grazie a dio hofatto scorrere@yeope Why is this the accepted answer!? thank god I scrolled
- 0
- 2019-10-21
- Juan Solano
-
non riuscivo afarlofunzionare.puoiindicare un sito con qualche spiegazione a questo?[niente qui,] (https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) che supportailtuo codicecouldn'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
Bene,vorreiesporre lamiaesperienzanell'ordinamento ditipi dipostpersonalizzatiper categoria/tassonomia.
IL WEB
- Sito web di un'agenzia di viaggiin esecuzione su WordPress
- Contenutoprincipale sultipo dipostpersonalizzato chiamato "ruta"
- Tassonomia con questa struttura Tipo di viaggio> continente>paese
IL CASO
Nellepagine dell'elenco delle categorie di archivio,il cliente desiderava ordinarei postin base a
- Il continente,ordinatopernumero di rotte su ciascuna diesse.
- Ilpaese,in ordine alfabetico.
I PASSAGGI
Innanzitutto ,prendo la richiesta dalla query dellapagina di archiviononmodificata che è risultataessere così:
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
Secondo ,homodificatoil codice sqlin Sequel Pro rispetto al databaseper soddisfare lemie esigenze. Esco con questo (sì,probabilmentepuòesseremigliorato:ilmio conoscenza su MySQLnon èeccezionale):
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
Terzo ,ho agganciato la query alfilefunctions.php contrefiltri:posts_fields,posts_joine posts_orderby
Il codicein 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; }
Infine ho attivatoi filtri dall'hookpre_get_postin base ad alcune condizioni
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');
Spero che questopossa aiutare qualcuno
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
-
Bel lavoro,ridicolo che sia stataimpiegata questa quantità di codiceper ordinare qualcosain base a unatassonomia.Enormeproblema con 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
Ho avuto unproblemamolto simile che ho affrontato: voglio ordinare un archivio dipost-typepersonalizzato (articoli di riviste)in base a unatassonomiapersonalizzata (problemi). Noneseguomai query SQL dirette sulmio sitoe di solito se sei come queste altre risposte devi ripensare altuo approccio.
PROBLEMI:
1) Wordpressnon consente di ordinaretassonomiein modointelligente.
2) Wordpress semplicementenon consente a
orderby
di utilizzaretassonomie su WP_Query ditipopost (come spiegato da Otto).SOLUZIONI:
1) L'ordinamento delletassonomie si ottiene almeglio con Plug-in Custom Taxonomy Order NE almomento. Tipermette di ordinare latassonomiatramite WYSIWYGin
wp-admin
chenon è come lofareiiomanon hotrovatoniente dimeglio.Quando configuriilplugin,otterrai qualcosa di simile a quello che hofatto qui. Prendinota dell'opzione
Auto-sort Queries of this Taxonomy
-impostala suCustom Order as Defined Above
; questoti dà l'ordine di cui haibisogno. Screenshot:2) Con unatassonomia ordinatain atto,è orapossibile creare una serie di chiamate WP_Query che attraversano ognitermine,creandoeffettivamente un archivio ordinato dallatassonomia. Utilizza
get_terms()
per creare un array dituttii terminifiscali,quindiesegui unforeach
su ciascuntermine. Questo crea unWP_Query
per ognielemento deltermine che restituiràtuttii postper un datotermine,creandoeffettivamente un archivio ordinatopertermine dellatassonomia. Codiceperfarlo accadere:// 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; }
Letture correlate su questo sito: Visualizzatuttii postin untipo dipostpersonalizzato,raggruppatoin base a unatassonomiapersonalizzata
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
Ecco la soluzione che ho usatoper questoparticolareproblema. Questa soluzione èper casiestremiin cuinon èpossibile utilizzare unfiltro
pre_get_posts
ed èpresente unapaginazioneesistente sulla query (adesempio: 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);
L'ho usatoper creare unmenu dinavigazione ordinatopertassonomia,terminee conteggio deipostpertermine.
Se desideri semplicementei post,modifica la queryin
SELECT p.*
eGROUP 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
È come una queryprima della query,manon sipreoccuperà senon stiamointerrogandotroppipost ... L'idea è dimodificare la queryprincipalein modo danon dovernemmeno andare aimodellie generarenuove querye cicli ...
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
mi piace ordinarei mieiterminimanualmente,quindi uso unpluginperfarlo.e sono unfan delfiltro
pre_get_posts
,quindi hopreso l'esempio di lavoro corretto di Drew Gourleye l'hofattofunzionare con quello. quindi questo è un caso speciale,ma lo sto comunquepubblicando,nel casoin cui aiuti qualcuno.il codice seguente vain functions.php oin unpluginpersonalizzato.perprima cosainiziamo conilfiltro. ordiniamoiltipo di articolopersonalizzato
music
in base allatassonomiapersonalizzatastyle
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');
quindi chiamiamoilfiltropost_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);
oratutto quello che devifare è ordinare letuetassonomie conil seguenteplugin: Ordinepostalepersonalizzato semplice . Questo plugin è obbligatorio per questa soluzione,poiché aggiunge la colonna
term_order
al database!e questa riga qui:
$clauses['orderby'] .= ", {$wpdb->posts}.post_name ASC"
ordinai postpertitolo,quindi l'ordinamento completo della soluzioneprecedente è:taxonomyterm=>titolo delpost.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.
Lamia domanda è semplice,sto usando
WP_Query
per recuperare alcunipost ditipopersonalizzatofiltrati da unatassonomia utilizzandotax_query
.Orailmioproblema è che vorrei
orderby
lataxonomy
,ma dalla documentazionee dalla ricerca sul Webnon riesco atrovare una soluzione.orderby
inWP_Query
ti consente di ordinarein base a una serie di campi anchei metacampipersonalizzati,manon sembra supportare latassonomia.Qualche suggerimentonellagiusta direzione?
Grazie atutti.