Obtenez toutes les catégories et tous les messages de ces catégories
-
-
rejetée car votreexigencetransforme cela d'une question WordPressen unproblème detriphp.downvoted as your requirement turns this from a WordPress question into a php sorting problem.
- 0
- 2012-02-25
- Michael
-
S'il vousplaît voirma réponse.Extrêmement rapideet efficace.Voir les statistiques quej'ai ajoutées dansma réponsePlease see my answer. Extremely quick and efficient. See the stats I've added in my answer
- 3
- 2014-09-07
- Pieter Goosen
-
Etpar là?** ** Vouspouvez alors apprendre à utiliser HTMLet css.How about by this? **** You can get how to use HTML and css then.
- 0
- 2018-10-16
- Vishwa
-
7 réponses
- votes
-
- 2017-06-24
Je voulaisjuste ajouterma solution dérivée de cette question quej'avais. Celamet en cache la requêtepour les catégorieset met égalementen cache lespublications,y compris le contenu de lapublication,dans chaque catégorie. Lapremièrefois que le cacheest rempli,il y a des requêtes debase de donnéesnormales,mais unefois remplies,les catégorieset lesmessagesen cache sont servis,doncplus de requêtes debase de données.
// Transients API all categories and all posts $query_categories = get_transient('cached_categories'); if ( false === $query_categories){ $args_cat = array( // order by category name ascending 'orderby' => 'name', 'order' => 'ASC', // get only top level categories 'parent' => 0 ); // Instead of caching a WP Query I cache 'get_categories()'. $query_categories = get_categories($args_cat); // var_dump($query_categories); set_transient('cached_categories', $query_categories, DAY_IN_SECONDS ); } // Full posts query // if there are categories filled with posts if (!empty ($query_categories) && !is_wp_error( $query_categories )) { foreach ($query_categories as $category) { // var_dump($category); $query_category_posts = get_transient('cached_posts_' . $category->slug ); if ( false === $query_category_posts ){ // Query all posts by slug inside each category $args_category_posts = array( 'post_type' => 'post', // The category slug and category name we get from the foreach over all categories 'category_name' => $category->slug ); // Here I cache the WP_Query, though this runs for all categories. // Because of that the '$category->slug' is used to serve a string and not an object. $query_category_posts = new WP_Query($args_category_posts); set_transient( 'cached_posts_' . $category->slug , $query_category_posts, DAY_IN_SECONDS ); } if ($query_category_posts->have_posts()) { while ($query_category_posts->have_posts()) { $query_category_posts->the_post(); ?> <article class="<?php echo $category->slug ?>-article"> <h2 class="<?php echo $category->slug ?>-article-title"> <a href="<?php echo get_permalink() ?>"><?php echo get_the_title() ?></a> </h2> <p class="<?php echo $category->slug ?>-post-info"> <?php the_time('d. m. Y') ?> </p> <div <?php post_class() ?> > <?php the_content(); ?> </div> </article> <?php } } // end loop } // end foreach wp_reset_postdata() ; } // end if there are categories filled with posts
I just wanted to add my solution that derived from this question I had. This caches the query for the categories and also caches the posts, including the post content, in each category. The first time the cache is filled there are normal database queries, however once filled the cached categories and posts are served, so no more database queries.
// Transients API all categories and all posts $query_categories = get_transient('cached_categories'); if ( false === $query_categories){ $args_cat = array( // order by category name ascending 'orderby' => 'name', 'order' => 'ASC', // get only top level categories 'parent' => 0 ); // Instead of caching a WP Query I cache 'get_categories()'. $query_categories = get_categories($args_cat); // var_dump($query_categories); set_transient('cached_categories', $query_categories, DAY_IN_SECONDS ); } // Full posts query // if there are categories filled with posts if (!empty ($query_categories) && !is_wp_error( $query_categories )) { foreach ($query_categories as $category) { // var_dump($category); $query_category_posts = get_transient('cached_posts_' . $category->slug ); if ( false === $query_category_posts ){ // Query all posts by slug inside each category $args_category_posts = array( 'post_type' => 'post', // The category slug and category name we get from the foreach over all categories 'category_name' => $category->slug ); // Here I cache the WP_Query, though this runs for all categories. // Because of that the '$category->slug' is used to serve a string and not an object. $query_category_posts = new WP_Query($args_category_posts); set_transient( 'cached_posts_' . $category->slug , $query_category_posts, DAY_IN_SECONDS ); } if ($query_category_posts->have_posts()) { while ($query_category_posts->have_posts()) { $query_category_posts->the_post(); ?> <article class="<?php echo $category->slug ?>-article"> <h2 class="<?php echo $category->slug ?>-article-title"> <a href="<?php echo get_permalink() ?>"><?php echo get_the_title() ?></a> </h2> <p class="<?php echo $category->slug ?>-post-info"> <?php the_time('d. m. Y') ?> </p> <div <?php post_class() ?> > <?php the_content(); ?> </div> </article> <?php } } // end loop } // end foreach wp_reset_postdata() ; } // end if there are categories filled with posts
-
- 2018-07-10
essayezmaintenant ce code
$cat_ids=array(); foreach (get_categories() as $cat) { array_push($cat_ids, $cat->cat_ID); } $the_query = new WP_Query(array('post_type'=>'post', array('category__and' => $cat_ids) ) ); if( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post(); echo the_title(); endwhile; endif; wp_reset_query();
try now this code
$cat_ids=array(); foreach (get_categories() as $cat) { array_push($cat_ids, $cat->cat_ID); } $the_query = new WP_Query(array('post_type'=>'post', array('category__and' => $cat_ids) ) ); if( $the_query->have_posts() ): while ( $the_query->have_posts() ) : $the_query->the_post(); echo the_title(); endwhile; endif; wp_reset_query();
-
- 2020-04-07
Voicima solutionpour obtenir les catégorieset lesmessages dans ces catégoriesen un seul résultat.
Monexempleestbasé sur la catégorie detaxonomie detype depublicationpersonnalisée
document_category
et letype depublicationpersonnalisédocuments
. Maisje suis sûr que vous comprendrez l'idée.$result = []; $categories = get_terms( [ 'taxonomy' => 'document_category' ] ); foreach ( $categories as $index => $category ) { $args = [ 'post_type' => 'documents', 'posts_per_page' => - 1, 'public' => true, 'tax_query' => [ [ 'taxonomy' => 'document_category', 'field' => 'term_id', 'terms' => $category->term_id, 'include_children' => true ] ] ]; $documents = get_posts( $args ); $result[ $index ]['category'] = $category; $result[ $index ]['documents'] = $documents; } return $result;
Here is my solution for getting the categories and the posts within those categories as one result.
My example is based on custom post type taxonomy category
document_category
and the custom post typedocuments
. But i'm sure you will get the idea.$result = []; $categories = get_terms( [ 'taxonomy' => 'document_category' ] ); foreach ( $categories as $index => $category ) { $args = [ 'post_type' => 'documents', 'posts_per_page' => - 1, 'public' => true, 'tax_query' => [ [ 'taxonomy' => 'document_category', 'field' => 'term_id', 'terms' => $category->term_id, 'include_children' => true ] ] ]; $documents = get_posts( $args ); $result[ $index ]['category'] = $category; $result[ $index ]['documents'] = $documents; } return $result;
-
- 2012-02-24
Vouspouvez utiliser ceci ... Définissez lenombre demessages dont vous avezbesoin ...
J'ai égalementtoutmis dans un div,pour que vouspuissiez créer la structureet la conception que vous recherchez.
<?php $allcats = get_categories('child_of=0'); foreach ($allcats as $cat) : $args = array( 'posts_per_page' => 3, // set number of post per category here 'category__in' => array($cat->term_id) ); $customInCatQuery = new WP_Query($args); if ($customInCatQuery->have_posts()) : echo '<div>'; echo '<h3>'.$cat->name.'</h3>'; echo '<ul>'; while ($customInCatQuery->have_posts()) : $customInCatQuery->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; echo '</ul></div>'; ?> <?php else : echo 'No post published in:'.$cat->name; endif; wp_reset_query(); endforeach; ?>
J'espère que cela vous aidera.
You can use this... Set the amount of posts you need...
Also I have put it all inside a div, so you can do the structure and design your looking for.
<?php $allcats = get_categories('child_of=0'); foreach ($allcats as $cat) : $args = array( 'posts_per_page' => 3, // set number of post per category here 'category__in' => array($cat->term_id) ); $customInCatQuery = new WP_Query($args); if ($customInCatQuery->have_posts()) : echo '<div>'; echo '<h3>'.$cat->name.'</h3>'; echo '<ul>'; while ($customInCatQuery->have_posts()) : $customInCatQuery->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; echo '</ul></div>'; ?> <?php else : echo 'No post published in:'.$cat->name; endif; wp_reset_query(); endforeach; ?>
Hope this helps.
-
Thx,maisprenons l'exemple de 10 catégories.Dans ce cas,votre codeprovoque 11 requêtes SQL.Je recherche 1 requête SQL.Lameilleure chose seraitprobablement d'obtenirtous lesmessages,classéspar catégorie,maisje ne saispas commentfaire cela (jen'aipastrouvé `order_by=cat` dans le codex)!?Thx, but take the example of say 10 categories. In that case your code causes 11 SQL queries. I am looking for 1 SQL query. The best thing would probably be to get all posts, ordered by category, but I don't know how to do that (I didn't find `order_by = cat` in the codex) !?
- 1
- 2012-02-24
- Ben
-
jene pensepas que ce soitimportant si ses 10 catégories ou 20 ... (essayé avec 20) àmoins que vousn'essayiez de charger ungrandnombre demessages qui,danstous les cas,pourraient ralentir le chargement de lapage ..essayez-le - voustrouverezc'est vraimentfacile -essayer de réorganiser après avoir chargé via des catégories signifierait construire un code énormeet surtoutinutile (àmon humble avis :))i dont think it matters one bit if its 10 categories or 20... (tried it with 20) unless you are trying to load a huge number posts which in any case might slow the page load.. try it - you'll find it real breezy - trying to rearrange after loaded via categories would mean building a huge and mostly useless code (to my humble opinion :) )
- 0
- 2012-02-24
- Sagive SEO
-
Non,il vous suffit demodifier légèrement la sortie (c'est-à-dire la liste defin pour le chatn et la liste de départpour le chatn + 1) à chaquefois qu'un article a une catégorie quiest différente de la catégorie de l'articleprécédent ... Beaucoupplus simple que debombarder votrepauvrebase de données avecplus de 20 requêtesparpage ... (àmon humble avis :)No it doesn't, you just need to change the output slightly (i.e. end list for cat n, and start list for cat n+1) everytime a post has a category that is different from the previous post's category... A lot simpler than bombarding your poor database with 20+ queries per pageload... (to my humble opinion :)
- 1
- 2012-02-25
- Ben
-
Jepense quenousposerions lamême question à labase de données,maisen ordonnant simplement les choses différemment à la sortie ..je ne voispas la différence ...en plus - c'est une requête logique .. "donnez-moi lepremier * de cette catégorie" ... donnez-moi lepremier * de cette catégorie "au lieu deme donner cemessage,encore unefois,encore unefois .. c'est de lamêmemanièremaisje transmets les données commej'en aibesoin ... sauf sije metrompe ..i think it would we asking the database the same question but just ordering stuff differently on the output end.. i dont see the difference... besides - its a logical query.. "give me the first * from this category"... give me the first * from that category" instead of give me that post, again, again, again.. its the same way but i am puling the data in the way i need it... unless i am mistaken..
- 0
- 2012-02-25
- Sagive SEO
-
La différenceest lenombre de requêtes db.Ungrand contreplusieurspetits ...;)The difference is the number of db queries. One big vs. many small... ;)
- 1
- 2012-02-25
- Ben
-
hmm ..ne saispas -ne le comprendspas dans cettemesure ..je veux dire lafaçon dont wordpress agit sur cette requête ..mais.J'aiessayéet jepense que çamarchetrès vite.j'espère aumoins raccourcir le chemin vers la solution souhaitée.;)hmm.. dont know - dont understand it to this extent.. i mean the way wordpress acts on this query.. but. i tried and i think it work really fast. i hope i at least shortend the way to your desired solution. ;)
- 0
- 2012-02-25
- Sagive SEO
-
O (n)inefficaceO(n) inefficient
- 0
- 2018-04-29
- S..
-
- 2012-02-24
J'ai construit quelque chosepourmoi quej'utilisebeaucoup,voici le code,vouspouvez utiliser des slugs,desidentifiants ou leterme objet dans letableau
$categories
,si vous vouleztout obtenir les catégories que vouspouvez utiliserget_terms()
,et alimenter avec untas d'objets determe,mais attention,iln'y apas detraitementpour la hiérarchie sur ce code.$categories = array( 1, 'slug', 3 ); echo '<ul>'; foreach($categories as $category) { $term = ( is_numeric($category) || is_object($category) ? get_term( $category, 'category' ) : get_term_by( 'slug', $category, 'category' ) ); $args = array( 'cat' => $term->term_id // Add any other arguments to fit your needs ); $q = new WP_Query( $args ); if( $q->have_posts() ) { echo '<li><a href="' . get_term_link( $term->term_id, 'category' ) . '">' . $term->name . '</a><ul>'; while( $q->have_posts() ) { $q->the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } echo '</ul></li>'; } else { } } echo '</ul>';
I've build something for me that I use quite alot, here is the code, you can use slugs, ids or the term object in the
$categories
array, if you want to get all the categories you can useget_terms()
, and feed with a bunch of term objects, but be careful, there is no treatment for hierarchy on this code.$categories = array( 1, 'slug', 3 ); echo '<ul>'; foreach($categories as $category) { $term = ( is_numeric($category) || is_object($category) ? get_term( $category, 'category' ) : get_term_by( 'slug', $category, 'category' ) ); $args = array( 'cat' => $term->term_id // Add any other arguments to fit your needs ); $q = new WP_Query( $args ); if( $q->have_posts() ) { echo '<li><a href="' . get_term_link( $term->term_id, 'category' ) . '">' . $term->name . '</a><ul>'; while( $q->have_posts() ) { $q->the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } echo '</ul></li>'; } else { } } echo '</ul>';
-
O (n2)inefficaceO(n2) inefficient
- 0
- 2018-04-29
- S..
-
- 2012-02-24
Nontesté,mais l'une des approches lesplus simples quej'essaieraisest la suivante:
<?php $category_ids = get_all_category_ids(); foreach ($category_ids as $values) { $args = array('category' => $value); $posts_array = get_posts( $args ); foreach ($posts_array as $post) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; wp_reset_query(); } ?>
Untested, yet one of the simplest approaches I would try is the following:
<?php $category_ids = get_all_category_ids(); foreach ($category_ids as $values) { $args = array('category' => $value); $posts_array = get_posts( $args ); foreach ($posts_array as $post) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; wp_reset_query(); } ?>
-
Mêmeproblème que le code de SagiveSame problem as Sagive's code
- 0
- 2012-02-24
- Ben
-
D'accord.Iln'y a aucunmoyen defaire une seule requête.Le chargement d'unepagepour Wordpress comporteplusieurs requêtestelles quelles,avant d'ajouter du codepersonnalisé.Toutes les requêtesintégrées utilisent la classe WPDB.La seulefaçon de lefaire dans une seule requêteest avec votrepropretransaction sql ouen faisant de WPDB une classeparentepour une autre classe à cettefin eten l'appelant de cettefaçon.ok. There is no way to get a single query done. Loading any page for Wordpress has multiple queries as it is, before adding custom code. All built-in queries use the WPDB class. The only way to do it in a single query is with your own transact sql or by making WPDB a parent class to another class for this purpose and calling it that way.
- 0
- 2012-03-04
- Neil Davidson
-
Nota que `get_all category_ids ();`est désormais obsolèteNota that `get_all_category_ids();` is now depreciated
- 0
- 2015-01-06
- Pieter Goosen
-
O (n)inefficaceO(n) inefficient
- 0
- 2018-04-29
- S..
-
- 2012-02-24
si vous recherchez unplugin, Répertoriez lesmessages de la catégorie pourraitfonctionnerpour vous.
Pour une requête,jetez un œil à
get_posts
if you are looking for a plugin, List Category Posts might work for you.
Fore a query, take a look at
get_posts
-
ou ceci aussi: http://codex.wordpress.org/Function_Reference/get_all_category_idsor this too: http://codex.wordpress.org/Function_Reference/get_all_category_ids
- 0
- 2012-02-24
- jasonflaherty
-
Thx,mais celan'aidepas.Thx, but that doesn't help.
- 0
- 2012-02-24
- Ben
Je recherche une solution quime permette d'imprimer ce qui suit:
Je cherche quelque chose quine nécessitera qu'une une requête debase de données!Donc,si vous avez un
foreach
dans votre code suivi d'unnew WP_Query
alors cen'estpas ce queje recherche (jeprévois de lemettre sur lapage d'accueil demon site Web).