Ottieni il genitore di primo livello di un termine di tassonomia personalizzata
7 risposta
- voti
-
- 2011-08-05
Grazie a Ivayloper questo codice,basato sulla risposta di Bainternet.
Laprimafunzione di seguito,
get_term_top_most_parent
,accetta unterminee unatassonomiae restituisceilgenitore diprimo livello deltermine (oiltermine stesso,se è senzagenitori); la secondafunzione (get_top_parents
)funzionanel cicloe,data unatassonomia,restituisce unelenco HTML deigenitori diprimo livello deitermini di unpost.// Determine the top-most parent of a term function get_term_top_most_parent( $term, $taxonomy ) { // Start from the current term $parent = get_term( $term, $taxonomy ); // Climb up the hierarchy until we reach a term with parent = '0' while ( $parent->parent != '0' ) { $term_id = $parent->parent; $parent = get_term( $term_id, $taxonomy); } return $parent; }
Una volta che hai lafunzione sopra,puoi scorrerei risultati restituiti da
wp_get_object_terms
e visualizzareilgenitoreprincipale di ognitermine:function get_top_parents( $taxonomy ) { // get terms for current post $terms = wp_get_object_terms( get_the_ID(), $taxonomy ); $top_parent_terms = array(); foreach ( $terms as $term ) { //get top level parent $top_parent = get_term_top_most_parent( $term, $taxonomy ); //check if you have it in your array to only add it once if ( !in_array( $top_parent, $top_parent_terms ) ) { $top_parent_terms[] = $top_parent; } } // build output (the HTML is up to you) $output = '<ul>'; foreach ( $top_parent_terms as $term ) { //Add every term $output .= '<li><a href="'. get_term_link( $term ) . '">' . $term->name . '</a></li>'; } $output .= '</ul>'; return $output; }
Thanks to Ivaylo for this code, which was based on Bainternet's answer.
The first function below,
get_term_top_most_parent
, accepts a term and taxonomy and returns the the term's top-level parent (or the term itself, if it's parentless); the second function (get_top_parents
) works in the loop, and, given a taxonomy, returns an HTML list of the top-level parents of a post's terms.// Determine the top-most parent of a term function get_term_top_most_parent( $term, $taxonomy ) { // Start from the current term $parent = get_term( $term, $taxonomy ); // Climb up the hierarchy until we reach a term with parent = '0' while ( $parent->parent != '0' ) { $term_id = $parent->parent; $parent = get_term( $term_id, $taxonomy); } return $parent; }
Once you have the function above, you can loop over the results returned by
wp_get_object_terms
and display each term's top parent:function get_top_parents( $taxonomy ) { // get terms for current post $terms = wp_get_object_terms( get_the_ID(), $taxonomy ); $top_parent_terms = array(); foreach ( $terms as $term ) { //get top level parent $top_parent = get_term_top_most_parent( $term, $taxonomy ); //check if you have it in your array to only add it once if ( !in_array( $top_parent, $top_parent_terms ) ) { $top_parent_terms[] = $top_parent; } } // build output (the HTML is up to you) $output = '<ul>'; foreach ( $top_parent_terms as $term ) { //Add every term $output .= '<li><a href="'. get_term_link( $term ) . '">' . $term->name . '</a></li>'; } $output .= '</ul>'; return $output; }
-
Mipiacerebbe vedere unamodifica chenon stampi soloi termini diprimo livelloma,piuttosto,tuttii termini al di sotto delgenitorepiùin alto,gerarchicamente.I'd love to see a modification that wouldn't just print out the top-level terms but, rather, all terms beneath the top-most parent, hierarchically.
- 0
- 2018-12-22
- Robert Andrews
-
@RobertAndrews Se hai solobisogno deifigli di un singolotermine,puoi usare `get_term_children ($term,$taxonomy)` ([documentazione] (https://codex.wordpress.org/Function_Reference/get_term_children)). Se si desidera otteneretuttii figli delgenitore diprimo livello di un datotermine,èpossibilepassareil risultato sopra riportato,in questomodo: `get_term_children (get_term_top_most_parent ($term,$taxonomy),$taxonomy)`.@RobertAndrews If you just need the children of a single term, you can use WordPress's built-in `get_term_children( $term, $taxonomy )` ([documentation](https://codex.wordpress.org/Function_Reference/get_term_children)). If you wanted to to get all children of a given term's top-level parent, you could pass the above result into it, like this: `get_term_children( get_term_top_most_parent( $term, $taxonomy ), $taxonomy )`.
- 0
- 2019-01-04
- supertrue
-
Qual è $termin questo caso,ades.l'oggetto,ilnome deltermine,ilprefissotaxonomyname_number?Intuttii casi,questometodo èestremamente lungo da caricare.Ho aspettato che lapagina si caricasse da diversiminuti.What is $term in this case, ie. the object, the name of the term, the prefixed taxonomyname_number? In all cases, this method is extremely long to load. I've been waiting for the page to load for several minutes now.
- 0
- 2019-01-04
- Robert Andrews
-
Come originariamente scritto,si aspettava un ID,ma homodificato la rispostaper consentire untermine ID o oggetto WP_Term. Non sei [l'unico] (https://wordpress.stackexchange.com/questions/63277/how-to-get-the-top-most-term-top-ancestor-of-a-custom-taxonomy-child-term? rq=1) segnala unproblema con questo codice -idealmente dovrebbeessere riscrittoper usare lafunzioneincorporata di WP `get_ancestors`,cheeranuovae nonben documentata quando la risposta è stata scritta.Pubblicherò unanuova risposta quando avròiltempo diprovare.As originally written it expected an ID, but I edited the answer to allow a term ID or WP_Term object. You're [not the only one](https://wordpress.stackexchange.com/questions/63277/how-to-get-the-top-most-term-top-ancestor-of-a-custom-taxonomy-child-term?rq=1) reporting an issue with this code—ideally it should be rewritten to use WP's built-in `get_ancestors` function, which was new and not well documented when the answer was written. I will post a new answer when I've had time to test.
- 1
- 2019-01-05
- supertrue
-
- 2013-06-17
Dalla 3.1.0,è disponibile
get_ancestors()
.Restituisce un array di antenati dalpiùbasso alpiù altonellagerarchia.Since 3.1.0,
get_ancestors()
is available. It returns an array of ancestors from lowest to highest in the hierarchy.-
Questa è la risposta corretta secondome.This is the correct answer in my opinion.
- 1
- 2015-07-05
- numediaweb
-
Questa è lamigliore risposta.This is the best answer.
- 1
- 2015-07-22
- Mark
-
- 2011-08-03
Ecco una semplicefunzione cheti daràilprimoterminepiùgenitore di un datotermine:
function get_term_top_most_parent( $term_id, $taxonomy ) { $parent = get_term_by( 'id', $term_id, $taxonomy ); while ( $parent->parent != 0 ){ $parent = get_term_by( 'id', $parent->parent, $taxonomy ); } return $parent; }
Una volta ottenuta questafunzione,puoi semplicemente scorrerei risultati restituiti da
wp_get_object_terms
:$terms = wp_get_object_terms( $post->ID, 'taxonomy' ); $top_parent_terms = array(); foreach ( $terms as $term ) { //Get top level parent $top_parent = get_term_top_most_parent( $term->ID, 'taxomony' ); //Check if you have it in your array to only add it once if ( !in_array( $top_parent->ID, $top_parent_terms ) ) { $top_parent_terms[] = $top_parent; } }
Here is a simple function that will get you the top most parent term of any given term:
function get_term_top_most_parent( $term_id, $taxonomy ) { $parent = get_term_by( 'id', $term_id, $taxonomy ); while ( $parent->parent != 0 ){ $parent = get_term_by( 'id', $parent->parent, $taxonomy ); } return $parent; }
Once you have this function you can just loop over the results returned by
wp_get_object_terms
:$terms = wp_get_object_terms( $post->ID, 'taxonomy' ); $top_parent_terms = array(); foreach ( $terms as $term ) { //Get top level parent $top_parent = get_term_top_most_parent( $term->ID, 'taxomony' ); //Check if you have it in your array to only add it once if ( !in_array( $top_parent->ID, $top_parent_terms ) ) { $top_parent_terms[] = $top_parent; } }
-
Grazie!Lo stoprovando adesso.Cordiali saluti,penso cheti manchi unaparentesi strettanella riga 1 dellafunzione.Thanks! I'm trying this now. FYI I think you're missing a close paren in line 1 of the function.
- 0
- 2011-08-03
- supertrue
-
devo aggiungere $taxonomy come secondoparametroin $top_parent?do I need to add $taxonomy as a second parameter in $top_parent?
- 0
- 2011-08-03
- supertrue
-
Ho aggiuntoilparametro $taxonomyma ricevo unerrore quando utilizzo questo codice,qui: https://gist.github.com/1122631I added the $taxonomy parameter but am getting an error when I use this code, here: https://gist.github.com/1122631
- 0
- 2011-08-03
- supertrue
-
si lofai.ho aggiornato la risposta.yeah you do. i updated the answer.
- 0
- 2011-08-03
- Bainternet
-
Con quello risolto,saiperchéil codice qui (http://gist.github.com/1122631)nonfunzionerebbe?With that fixed, do you know why the code here (http://gist.github.com/1122631) wouldn't be working?
- 0
- 2011-08-03
- supertrue
-
latuafunzione sembrainterrottai tuoi loopforeach si sovrappongonoprova questo: http://pastebin.com/u48dxzap e se ricevi ancora unerrore,incollatuttoil codicee io controlleròyour function seems broken your foreach loops are overlapping try this: http://pastebin.com/u48dxzap and if you still get an error paste all of you code and i'll check
- 1
- 2011-08-03
- Bainternet
-
Dà ancora lo stessoerrore;seprint_r ($top_parent_terms),ottengo un array vuoto,quindiforseilproblema èeffettivamente con laprimafunzione?Lamia versione qui - http://pastebin.com/cMUxs9NnIt still gives the same error; if I print_r($top_parent_terms), I get an empty array, so maybe the problem is actually with the first function? My version here - http://pastebin.com/cMUxs9Nn
- 0
- 2011-08-03
- supertrue
-
OK,pensa cheilproblema sia con `get_the_ID` chefunzionanel ciclo quindiprova questo: http://pastebin.com/u48dxzapOK think the problem is with `get_the_ID` which works in the loop so try this: http://pastebin.com/u48dxzap
- 0
- 2011-08-03
- Bainternet
-
@Bainternet cipermette di [continuare questa discussionein chat] (http://chat.stackexchange.com/rooms/985/discussion-between-supertrue-and-bainternet)@Bainternet let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/985/discussion-between-supertrue-and-bainternet)
- 0
- 2011-08-03
- supertrue
-
@ Bainternet-hapostato automaticamente quelmessaggio di chat?Per quanto riguarda $poste post-> IDglobale,lo sto usandonei cicli WP_Query quindiget_the_ID dovrebbefunzionare.@Bainternet-it automatically posted that chat message? Re global $post and post->ID, I am using this within WP_Query loops so get_the_ID should be working.
- 0
- 2011-08-03
- supertrue
-
No,lo stai usandoin unafunzione chiamata dal loop,funziona?No you are using it in a function called by the loop, does it work?
- 0
- 2011-08-03
- Bainternet
-
- 2013-10-18
/** * Ottienitermine diprimo livello */ funzioneget_top_level_term ($term,$taxonomy) { if ($term- >parent==0) restituisce $term; $parent=get_term ($term- >parent,$taxonomy); returnget_top_level_term ($parent,$taxonomy); } /** * Get top level term */ function get_top_level_term($term,$taxonomy){ if($term->parent==0) return $term; $parent = get_term( $term->parent,$taxonomy); return get_top_level_term( $parent , $taxonomy ); }
-
Siprega di aggiungere una spiegazioneinsieme al codice.Please add an explanation along with your code.
- 1
- 2013-10-18
- s_ha_dum
-
- 2014-10-30
Ho avuto lo stessoproblemae l'ho risoltofacilmente. Controlla questo:
Definisci
$taxonomy
. Puòessere lo slug dellatassonomia di cui vuoi ottenerei dati. Dopo averlofatto,puoi semplicementefarlo:<?php $postterms = wp_get_post_terms($post->ID, $taxonomy); // get post terms $parentId = $postterms[0]->parent; // get parent term ID $parentObj = get_term_by('id', $parentId, $taxonomy); // get parent object ?>
Ora hai qualcosa delgenere:
object(stdClass)#98 (11) { ["term_id"]=> int(3) ["name"]=> string(8) "Esportes" ["slug"]=> string(8) "esportes" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(3) ["taxonomy"]=> string(17) "noticiaseditorias" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(4) ["object_id"]=> int(123) ["filter"]=> string(3) "raw" }
Epuoi usare
$parentObj
per ottenere slug,nome,id,qualunque cosa. Semplicemente utilizzando$parentObj->slug
o$parentObj->name
comeesempio.I had the same problem and I solved easily. Check this out:
Define
$taxonomy
. It can be the slug of the taxonomy you want to get the data. After doing this, you can simply do this:<?php $postterms = wp_get_post_terms($post->ID, $taxonomy); // get post terms $parentId = $postterms[0]->parent; // get parent term ID $parentObj = get_term_by('id', $parentId, $taxonomy); // get parent object ?>
Now you got something like this:
object(stdClass)#98 (11) { ["term_id"]=> int(3) ["name"]=> string(8) "Esportes" ["slug"]=> string(8) "esportes" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(3) ["taxonomy"]=> string(17) "noticiaseditorias" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(4) ["object_id"]=> int(123) ["filter"]=> string(3) "raw" }
And you can use
$parentObj
to get slug, name, id, whatever. Just by using$parentObj->slug
or$parentObj->name
as exemple. -
- 2016-01-29
Ilmodopiù semplice:
$rootId = end( get_ancestors( $term_id, 'my_taxonomy' ) ); $root = get_term( $rootId, 'my_taxonomy' ); echo $root->name;
Easiest way:
$rootId = end( get_ancestors( $term_id, 'my_taxonomy' ) ); $root = get_term( $rootId, 'my_taxonomy' ); echo $root->name;
-
- 2015-12-11
Forse questo aiuta:
get_ancestors( $object_id, $object_type );
Maybe this helps:
get_ancestors( $object_id, $object_type );
Comeposso ottenereilgenitore diprimo livello di un datotermine?
Sto utilizzando
wp_get_object_terms
per ottenerei termini dellatassonomia suipost,mainvece dimostraretuttii termini contrassegnati,desideromostrare soloi genitori diprimo livello deitermini contrassegnati.Quindi,se questi sonoi termini selezionati,desidero visualizzare solo Colazione,pranzoe cena.
Comepossofarlo?