Affichage de la sous-catégorie actuelle
-
-
Jene comprendspas votre question."Je suis dans laboucle. Je voudrais afficher lenom de la sous-catégorie actuelle den'importe quelle catégorieparente".Que voulez-vous dire?I don't understand your question. "I am within the Loop. I would like to show the current subcategory name from any parent category". What do you mean?
- 0
- 2014-05-29
- Pieter Goosen
-
Vous devez donc affichertoutes les sous-catégories detoutes les catégoriesparentes.Jene peuxpas comprendre votreboucle cependant.Etpourquoi utilisez-vous `query_posts`iciSo you need to display all sub-categories from all parent categories. I can't understand your loop though. And why are you using `query_posts` here
- 0
- 2014-05-29
- Pieter Goosen
-
J'aibesoin d'afficher la sous-catégorie actuelle de cemessage de cette catégorieparent spécifique (événements).Veuillezignorer QUERY_POSTS.J'ai supprimé lebit oùj'appelle letitre,le contenuet laméta desmessagesI need to display current subcategory of that post from that specific parent category (Events). Please disregard QUERY_POSTS. I removed the bit where I call the title, the content and the meta from the posts
-
Ok,ça a du sensOk, that makes sense
- 0
- 2014-05-29
- Pieter Goosen
-
Je ***fortement *** déconseille d'utiliser `query_posts`,vousne devezpas l'utiliser,utilisez`get_posts`,`pre_get_posts` ou` WP_Query` à laplaceI ***strongly*** recommend against using `query_posts`, you must not use it, use `get_posts`, `pre_get_posts`, or `WP_Query` instead
- 1
- 2014-06-03
- Tom J Nowell
-
Pouvez-vous également reformuler unpeu votre question?Ilest difficile de déterminer dans queltype demodèle vous l'utilisez,si vous souhaitez l'utiliser à l'intérieur ou à l'extérieur de laboucle,veuillezfournir desexempleset un contexte supplémentaireAlso can you rephrase your question a little? It's difficult to figure out what kind of template you're using this in, if you want to use it inside or outside the loop, please provide examples and additional context
- 2
- 2014-06-03
- Tom J Nowell
-
1 réponses
- votes
-
- 2014-05-29
Tout d'abord,vous ne devezpas utiliser
query_posts
pourexécuter des requêtespersonnalisées. Du codex lui-mêmeRemarque: Cettefonctionn'estpas destinée à être utiliséepar desplugins ou desthèmes. Commeexpliquéplus loin,ilexiste demeilleures optionsplusperformantespourmodifier la requêteprincipale. query_posts ()est unmoyentrop simplisteet problématique demodifier la requêteprincipale d'unepageen la remplaçantpar unenouvelleinstance de la requête. Ilestinefficace (réexécute les requêtes SQL)et échouera carrément dans certaines circonstances (surtout souvent lors de lapagination des articles). Tout code WPmoderne devrait utiliser desméthodesplusfiables,comme l'utilisation du hookpre_get_posts,à cettefin.
Vous devriez utiliser
WP_Query
pour cette requêtepersonnalisée$args = array( 'category_name' => 'events', 'posts_per_page' => 2, 'offset' => 1 ); $myquery = new WP_Query( $args ); while ($myquery->have_posts()) : $myquery->the_post(); <-----YOUR LOOP CONTENTS-----> endwhile; wp_reset_postdata();
MODIFIER 1 & amp; MODIFIER 2
--SCRAPPÉ--
MODIFIER 3
Voici un contournement du code de
wp_list_categories()
.Vous devez d'abord obtenir l'ID de la catégorieparenteen utilisant
get_the_category()
$categories = get_the_category(); $parentid = $categories[0]->category_parent;
Cet IDparentpeutensuite être renvoyé à
wp_list_categories()
pourn'afficher que les catégoriesenfants de ceparent spécifique. Si aucune catégorieenfantn'existe,il renverra lenom de la catégorieparent,sinon si leparent a desenfants,les catégoriesenfants seront retournéesVoici lafonction complète
<?php $taxonomy = 'category'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; $categories = get_the_category(); $parentid = $categories[0]->category_parent; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&child_of=' . $parentid . '&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?>
First of all, you should not be using
query_posts
to run custom queries. From the codex itselfNote: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.
You should be using
WP_Query
for this custom query$args = array( 'category_name' => 'events', 'posts_per_page' => 2, 'offset' => 1 ); $myquery = new WP_Query( $args ); while ($myquery->have_posts()) : $myquery->the_post(); <-----YOUR LOOP CONTENTS-----> endwhile; wp_reset_postdata();
EDIT 1 & EDIT 2
--SCRAPPED--
EDIT 3
Here is a work around of the code from
wp_list_categories()
.You first need to get the parent category's ID using
get_the_category()
$categories = get_the_category(); $parentid = $categories[0]->category_parent;
This parent ID can then be passed back to
wp_list_categories()
to only show the child categories of that specific parent. If no child category exists, it will return the parent category name, otherwise if the parent have children, the child categories will be returnedHere is the complete function
<?php $taxonomy = 'category'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ', '; $categories = get_the_category(); $parentid = $categories[0]->category_parent; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&child_of=' . $parentid . '&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?>
-
J'aiessayé le codepour afficher la sous-catégorie.Il y a unpoint dans la dernièreboucle quiproduit uneerreur.Après avoirnettoyé cepoint,je vois que le résultatest lemême:tous lesnoms de sous-catégories sont affichés.Troisièmement,est-ilnécessaire de déclarer $post_child_cat?P.s.Merci,j'ai remplacé lebit de requêtepersonnalisé.I tried the code for displaying the subcategory. There is a dot in the last loop that produces an error. After cleaning that dot out, I see the result is the same: all the subcategories names are displayed. Third, is declaring $post_child_cat necessary? P.s. Thank you, I replaced the custom query bit.
-
L'avez-vousfaitfonctionner?Did you get it working?
- 0
- 2014-05-29
- Pieter Goosen
-
J'ai un autretravail qui devraitfaire l'affairemaintenant.J'espère que EDIT 3 voudra que vous ayezbesoin.I have another work around that should do the trick now. I hope EDIT 3 will do want you need.
- 0
- 2014-06-02
- Pieter Goosen
-
Toujourspas de chance,maismerci!J'ai 3 articles sur lapage d'accueilet tous appartiennent à la catégorie "Événements".Votre solutionfonctionnepour les articles qui,en plus de la catégorie «Événements»,sont dans la sous-catégorie «Conférences»,maispaspour les articles appartenant,en plus de la catégorie «Événements»,à la sous-catégorie «Écoles d'été».Je suispresque sûr que cela a à voir avec un étrange ordre alphabétique Wordpresspar défautpour lesnoms de catégories.Still no luck, but thank you! I have 3 posts on the homepage and all of them belong to "Events" category. Your solution works for posts that, besides "Events" category, are in "Conferences" subcategory, but not for posts belonging, besides "Events" category, to "Summer Schools" subcategory. I am almost sure it has to do with some strange default Wordpress alphabetic ordering for category names.
-
Les «événements» sont-ils une catégorieparente ou unetaxonomie.Ilest assez difficile de comprendre quemon codene fonctionnepas uniquementpour les "événements".Essayez de coller ceci dans votre code,vérifiez ce qu'ilproduit sur lesmessages "Événements" .` $ categories=get_the_category (); $parentid=$ categories [0] -> category_parent;echo $parentid; `Are "Events" a parent category, or a taxonomy. Is is quite hard to understand that my code is not working for only "Events". Try pasting this in your code, check what it outputs on the "Events" posts.`$categories = get_the_category(); $parentid = $categories[0]->category_parent; echo $parentid;`
- 0
- 2014-06-02
- Pieter Goosen
-
Il devrait vousfournir une valeurnumérique,c'est l'ID de la catégorieparente.Ilne doitpas afficher un «0».«0» signifie qu'iln'y apas de sous-catégoriesIt should output you a numerical value, this is the ID of the parent category. It should not output a `0`. `0` means that there is no sub categories
- 0
- 2014-06-02
- Pieter Goosen
-
J'ai suivi votreindication.Lepost dans "Summer Schools" sort 0,lepost dans "Conferences" sort 3. Quoi qu'ilen soitje pense qu'ilestintéressant dejeter un œil à la succession dans laquelle les catégories sont stockées dans letableau: [lien] (http://i.imgur.com/GoRIt8P.png)I followed your indication. The post in "Summer Schools" outputs 0, the post in "Conferences" outputs 3. Anyway I believe it is interesting to take a look at the succession in which the categories are stored in the array: [link](http://i.imgur.com/GoRIt8P.png)
-
Quelleest la relationentre "Summer Schools"et "Events".Selon un «0» renvoyé,celamontre que les deux sont desparents quin'ontpas d'enfants.What is the relationship between "Summer Schools" and "Events". According to a `0` been returned, it shows both are parents that have no children.
- 0
- 2014-06-03
- Pieter Goosen
-
Ok,je suis stupéfaitici."Summer Schools"n'estpas,pour une raison quelconque,enregistré commeenfant de "Events".Il s'inscriten tant queparentOk, I'm dumbstruck here. "Summer Schools" is for some reason not been registered as a child of "Events". It is registers as a parent
- 0
- 2014-06-03
- Pieter Goosen
J'ai unproblème.
Je voudrais afficher lenom de la sous-catégorie actuelle den'importe quelle catégorieparente.
Avec cela,je neparviens qu'à affichertous lesnoms de sous-catégories duparent spécifié ...
Jen'aipas utilisé
the_category()
caril affiche lesnoms de sous-chatsenveloppés dans une listeet je voudrais qu'ils soient sansbalisage.