Récupère le parent de premier niveau d'un terme de taxonomie personnalisé
7 réponses
- votes
-
- 2011-08-05
Merci à Ivaylopour ce codebasé sur la réponse de Bainternet.
Lapremièrefonction ci-dessous,
get_term_top_most_parent
,accepte untermeet unetaxonomieet renvoie leparent deniveau supérieur duterme (ou leterme lui-même,s'ilest sansparent); la deuxièmefonction (get_top_parents
)fonctionne dans laboucle,et,étant donné unetaxonomie,renvoie une liste HTML desparents depremierniveau destermes d'un article.// 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; }
Unefois que vous avez lafonction ci-dessus,vouspouvezboucler sur les résultats renvoyéspar
wp_get_object_terms
et afficher leparentprincipal de chaqueterme: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; }
-
J'adorerais voir unemodification quin'imprimeraitpas seulement lestermes depremierniveaumais,plutôt,tous lestermes sous leparent leplus élevé,hiérarchiquement.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 Si vousn'avezbesoin que desenfants d'un seulterme,vouspouvez utiliser `get_term_children ($term,$taxonomy)` ([documentation] (https://codex.wordpress.org/Function_Reference/get_term_children))intégré à WordPress. Si vous vouliez obtenirtous lesenfants duparent depremierniveau d'unterme donné,vouspouvez luitransmettre le résultat ci-dessus,comme ceci: `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
-
Qu'est-ce que $term dans ce cas,ie.l'objet,lenom duterme,lepréfixetaxonomyname_number?Danstous les cas,cetteméthodeestextrêmement longue à charger.J'attends le chargement de lapage depuisplusieursminutesmaintenant.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
-
Commeinitialement écrit,il attendait un ID,maisj'aimodifié la réponsepour autoriser un ID determe ou un objet WP_Term. Vous [n'êtespas le seul] (https://wordpress.stackexchange.com/questions/63277/how-to-get-the-top-most-term-top-ancestor-of-a-custom-taxonomy-child-term? rq=1) signalant unproblème avec ce code -idéalement,il devrait être réécritpour utiliser lafonctionintégrée `get_ancestors` de WP,qui étaitnouvelleet mal documentée lorsque la réponse a été écrite.Jepublierai unenouvelle réponse lorsquej'auraieu letemps detester.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
Depuis la version 3.1.0,
get_ancestors()
est disponible.Il renvoie untableau d'ancêtres duplusbas auplus élevé dans la hiérarchie.Since 3.1.0,
get_ancestors()
is available. It returns an array of ancestors from lowest to highest in the hierarchy.-
C'est labonne réponse àmon avis.This is the correct answer in my opinion.
- 1
- 2015-07-05
- numediaweb
-
C'est lameilleure réponse.This is the best answer.
- 1
- 2015-07-22
- Mark
-
- 2011-08-03
Voici unefonction simple qui vouspermettra d'obtenir leterme leplusparent d'unterme donné:
functionget_term_top_most_parent ($term_id,$taxonomy) { $parent=get_term_by ('id',$term_id,$taxonomie); while ($parent- >parent!=0) { $parent=get_term_by ('id',$parent- >parent,$taxonomie); } return $parent; }
$terms=wp_get_object_terms ($post- > ID,'taxonomie'); $top_parent_terms=tableau (); foreach ($terms as $term) { //Obtenir leparent deniveau supérieur $top_parent=get_term_top_most_parent ($terme- > ID,'taxomonie'); //Vérifiez si vous l'avez dans votretableaupourne l'ajouter qu'une seulefois 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; } }
-
Merci!J'essaye çamaintenant.Pourinfo,je pense que vousmanquez unparenproche dans la ligne 1 de lafonction.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
-
dois-je ajouter $taxonomy comme deuxièmeparamètre dans $top_parent?do I need to add $taxonomy as a second parameter in $top_parent?
- 0
- 2011-08-03
- supertrue
-
J'ai ajouté leparamètre $taxonomymaisj'obtiens uneerreur lorsquej'utilise ce code,ici: 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
-
ouaistufais.J'aimis àjour la réponse.yeah you do. i updated the answer.
- 0
- 2011-08-03
- Bainternet
-
Avec cela corrigé,savez-vouspourquoi le codeici (http://gist.github.com/1122631)ne fonctionneraitpas?With that fixed, do you know why the code here (http://gist.github.com/1122631) wouldn't be working?
- 0
- 2011-08-03
- supertrue
-
votrefonction semble cassée vosbouclesforeach se chevauchentessayez ceci: http://pastebin.com/u48dxzap et si vous obteneztoujours uneerreur,colleztout votre codeet je vérifieraiyour 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
-
Cela donnetoujours lamêmeerreur;sij'imprime_r ($top_parent_terms),j'obtiens untableau vide,alorspeut-être que leproblème vienten fait de lapremièrefonction?Ma versionici - 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
-
OKpense que leproblème vient de `get_the_ID` quifonctionne dans laboucle,alorsessayez ceci: 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 laissez-nous [continuer cette discussion dans le 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-il a automatiquementposté cemessage de discussion?Concernant $postet post-> IDglobaux,j'utilise ceci dans lesboucles WP_Query,doncget_the_ID devraitfonctionner.@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
-
Non,vous l'utilisez dans unefonction appeléepar laboucle,çamarche?No you are using it in a function called by the loop, does it work?
- 0
- 2011-08-03
- Bainternet
-
- 2013-10-18
/** * 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 ); }
/** * 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 ); }
-
Veuillez ajouter uneexplication avec votre code.Please add an explanation along with your code.
- 1
- 2013-10-18
- s_ha_dum
-
- 2014-10-30
J'aieu lemêmeproblèmeet je l'ai résolufacilement. Vérifiez ceci:
Définissez
$taxonomy
. Celapeut être la limite de lataxonomie dont vous souhaitez obtenir les données. Après cela,vouspouvez simplementfaire ceci:<?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 ?>
Vous avezmaintenant quelque chose comme ceci:
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" }
Et vouspouvez utiliser
$parentObj
pour obtenir le slug,lenom,l'identifiant,peuimporte. Simplementen utilisant$parentObj->slug
ou$parentObj->name
commeexemple.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
Moyen leplus simple:
$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
Peut-être que cela aide:
get_ancestors( $object_id, $object_type );
Maybe this helps:
get_ancestors( $object_id, $object_type );
Commentpuis-je obtenir leparent depremierniveau d'unterme donné?
J'utilise
wp_get_object_terms
pour obtenir destermes detaxonomie sur les articles,mais au lieu d'affichertous lestermesbalisés,je souhaite uniquement afficher lesparents depremierniveau destermesbalisés.Donc,si ce sontmestermes sélectionnés,je souhaite uniquement afficher lepetit-déjeuner,le déjeuneret le dîner.
Commentpuis-jefaire cela?