Comment réparer la pagination pour les boucles personnalisées?
4 réponses
- votes
-
- 2015-11-09
J'utilise ce codepour unebouclepersonnalisée avecpagination:
<?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page $paged = get_query_var('page'); } else { $paged = 1; } $custom_query_args = array( 'post_type' => 'post', 'posts_per_page' => get_option('posts_per_page'), 'paged' => $paged, 'post_status' => 'publish', 'ignore_sticky_posts' => true, //'category_name' => 'custom-cat', 'order' => 'DESC', // 'ASC' 'orderby' => 'date' // modified | title | name | ID | rand ); $custom_query = new WP_Query( $custom_query_args ); if ( $custom_query->have_posts() ) : while( $custom_query->have_posts() ) : $custom_query->the_post(); ?> <article <?php post_class(); ?>> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small> <div><?php the_excerpt(); ?></div> </article> <?php endwhile; ?> <?php if ($custom_query->max_num_pages > 1) : // custom pagination ?> <?php $orig_query = $wp_query; // fix for pagination to work $wp_query = $custom_query; ?> <nav class="prev-next-posts"> <div class="prev-posts-link"> <?php echo get_next_posts_link( 'Older Entries', $custom_query->max_num_pages ); ?> </div> <div class="next-posts-link"> <?php echo get_previous_posts_link( 'Newer Entries' ); ?> </div> </nav> <?php $wp_query = $orig_query; // fix for pagination to work ?> <?php endif; ?> <?php wp_reset_postdata(); // reset the query else: echo '<p>'.__('Sorry, no posts matched your criteria.').'</p>'; endif; ?>
Source:
I use this code for custom loop with pagination:
<?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { // 'page' is used instead of 'paged' on Static Front Page $paged = get_query_var('page'); } else { $paged = 1; } $custom_query_args = array( 'post_type' => 'post', 'posts_per_page' => get_option('posts_per_page'), 'paged' => $paged, 'post_status' => 'publish', 'ignore_sticky_posts' => true, //'category_name' => 'custom-cat', 'order' => 'DESC', // 'ASC' 'orderby' => 'date' // modified | title | name | ID | rand ); $custom_query = new WP_Query( $custom_query_args ); if ( $custom_query->have_posts() ) : while( $custom_query->have_posts() ) : $custom_query->the_post(); ?> <article <?php post_class(); ?>> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small> <div><?php the_excerpt(); ?></div> </article> <?php endwhile; ?> <?php if ($custom_query->max_num_pages > 1) : // custom pagination ?> <?php $orig_query = $wp_query; // fix for pagination to work $wp_query = $custom_query; ?> <nav class="prev-next-posts"> <div class="prev-posts-link"> <?php echo get_next_posts_link( 'Older Entries', $custom_query->max_num_pages ); ?> </div> <div class="next-posts-link"> <?php echo get_previous_posts_link( 'Newer Entries' ); ?> </div> </nav> <?php $wp_query = $orig_query; // fix for pagination to work ?> <?php endif; ?> <?php wp_reset_postdata(); // reset the query else: echo '<p>'.__('Sorry, no posts matched your criteria.').'</p>'; endif; ?>
Source:
-
- 2016-12-17
Génial commetoujours Chip. En complément,considérez la situation dans laquelle vous utilisez unmodèle depageglobal attaché à unepagepour un "texte d'introduction"et ilest suivi d'une sous-requête que vous souhaitezpaginer.
En utilisant paginate_links () comme vous l'avezmentionné ci-dessus,avec des valeurspar défautpour laplupart,(eten supposant que vous avezjolispermaliens activés) vos liens depagination serontpar défaut
mysite.ca/page-slug/page/#
ce quiestjolimaisgénérera deserreurs404
car WordPressne saitpas àpropos de cette structure d'URLparticulièreet rechercheraen fait unepageenfant de "page" quiest unenfant de "page-slug".L'astuceiciest d'insérer une règle de réécriture astucieuse quine s'applique qu'à ce slug depage "pseudo-page d'archive"particulier qui accepte la structure
/page/#/
et la réécriten une chaîne de requête qui WordPress PEUT comprendre,à savoirmysite.ca/?pagename=page-slug&paged=#
. Notezpagename
etpaged
pasname
etpage
(ce quim'a causé littéralement des HEURES de chagrin,motivant cette réponseici! ).Voici la règle de redirection:
add_rewrite_rule( "page-slug/page/([0-9]{1,})/?$", 'index.php?pagename=page-slug&paged=$matches[1]', "top" );
Commetoujours,lorsque vousmodifiez les règles de réécriture,n'oubliezpas de vider vospermaliens en visitant Paramètres> Permaliens dans leback-end d'administration.
Si vous avezplusieurspages qui vont se comporter de cettefaçon (parexemple,lorsque voustraitez avecplusieurstypes depublicationpersonnalisés),vouspouvez éviter de créer unenouvelle règle de réécriturepour chaque slug depage. Nouspouvons écrire uneexpression régulièreplusgénérique quifonctionnepourn'importe quel slug depage que vousidentifiez.
Une approcheest ci-dessous:
function wpse_120407_pseudo_archive_rewrite(){ // Add the slugs of the pages that are using a Global Template to simulate being an "archive" page $pseudo_archive_pages = array( "all-movies", "all-actors" ); $slug_clause = implode( "|", $pseudo_archive_pages ); add_rewrite_rule( "($slug_clause)/page/([0-9]{1,})/?$", 'index.php?pagename=$matches[1]&paged=$matches[2]', "top" ); } add_action( 'init', 'wpse_120407_pseudo_archive_rewrite' );
Inconvénients/misesen garde
Uninconvénient de cette approche quime fait vomir unpeu dansmaboucheest le codageen dur du slug depage. Si un administrateurmodifie le slug depage de cettepseudo-archive,vousportez untoast - la règle de réécriturene correspondrapluset vous obtiendrez le redouté 404.
Jene suispas sûr depouvoirpenser à une solution de contournementpour cetteméthode,mais ce seraitbien si c'était lemodèle depageglobal qui a déclenché d'unemanière ou d'une autre la règle de réécriture. Unjour,je reviendraipeut-être sur cette réponse sipersonne d’autren’a réussi à résoudre ceproblème.
Awesome as always Chip. As an addendum to this, consider the situation whereby you are using a global page template attached to a Page for some "intro text" and it's followed by a subquery that you want to be paged.
Using paginate_links() as you mention above, with mostly defaults, (and assuming you have pretty permalinks turned on) your pagination links will default to
mysite.ca/page-slug/page/#
which is lovely but will throw404
errors because WordPress doesn't know about that particular URL structure and will actually look for a child page of "page" that's a child of "page-slug".The trick here is to insert a nifty rewrite rule that only applies to that particular "pseudo archive page" page slug that accepts the
/page/#/
structure and rewrites it to a query string that WordPress CAN understand, namelymysite.ca/?pagename=page-slug&paged=#
. Notepagename
andpaged
notname
andpage
(which caused me literally HOURS of grief, motivating this answer here!).Here's the redirect rule:
add_rewrite_rule( "page-slug/page/([0-9]{1,})/?$", 'index.php?pagename=page-slug&paged=$matches[1]', "top" );
As always, when changing rewrite rules, remember to flush your permalinks by visiting Settings > Permalinks in the Admin back-end.
If you have multiple pages that are going to behave this way (for example, when dealing with multiple custom post types), you might want to avoid creating a new rewrite rule for each page slug. We can write a more generic regular expression that works for any page slug you identify.
One approach is below:
function wpse_120407_pseudo_archive_rewrite(){ // Add the slugs of the pages that are using a Global Template to simulate being an "archive" page $pseudo_archive_pages = array( "all-movies", "all-actors" ); $slug_clause = implode( "|", $pseudo_archive_pages ); add_rewrite_rule( "($slug_clause)/page/([0-9]{1,})/?$", 'index.php?pagename=$matches[1]&paged=$matches[2]', "top" ); } add_action( 'init', 'wpse_120407_pseudo_archive_rewrite' );
Disadvantages / Caveats
One disadvantage of this approach that makes me puke in my mouth a little is the hard-coding of the Page slug. If an admin ever changes the page slug of that pseudo-archive page, you're toast - the rewrite rule will no longer match and you'll get the dreaded 404.
I'm not sure I can think of a workaround for this method, but it would be nice if it were the global page template that somehow triggered the rewrite rule. Some day I may revisit this answer if no one else has cracked that particular nut.
-
Vouspouvez accrocherpost save,vérifier si lapage a votremodèle d'archive sous la cléméta `_wp_page_template`,puis ajouter une autre règle de réécritureet de vidage.You could hook post save, check if the page has your archive template under the meta key `_wp_page_template`, then add another rewrite and flush rules.
- 1
- 2016-12-17
- Milo
-
- 2017-01-13
J'aimodifié la requête de laboucleprincipale via
query_posts()
. Pourquoi lapaginationne fonctionne-t-ellepaset comment y remédier?Excellente réponse Lapuce créée doit êtremodifiée aujourd'hui.
Depuis un certaintemps,nous avons la variable$wp_the_query
qui devrait être égale à la$wp_query
globalejuste après l'exécution de la requêteprincipale.C'estpourquoi voici lapartie de la réponse de lapuce:
Pirater l'objet de requêteprincipal
n'estplusnécessaire. Nouspouvons oublier cettepartie avec la création de la variabletemporaire.
// Pagination fix $temp_query = $wp_query; $wp_query = NULL; $wp_query = $custom_query;
Alorsmaintenant,nouspouvons appeler:
$wp_query = $wp_the_query;
oumieuxencore,nouspouvons appeler:
wp_reset_query();
Tout ce que les autres Chip ont décrit reste. Après cettepartie query-reset,vouspouvez appeler lesfonctions depagination qui sont
f($wp_query)
,-elles dépendent de$wp_query
global.Afin d'améliorerencore lesmécanismes depaginationet de donnerplus de liberté à lafonction
query_posts
,j'ai créé cette améliorationpossible:I have modified the main loop query via
query_posts()
. Why isn't pagination working, and how do I fix it?Great answer Chip created needs to be modified today.
For some time we have$wp_the_query
variable that should be equal to the$wp_query
global just after the main query executes.This is why this the part from the Chip's answer:
Hack the main query object
is not needed anymore. We can forget this part with creating the temporary variable.
// Pagination fix $temp_query = $wp_query; $wp_query = NULL; $wp_query = $custom_query;
So now we can call:
$wp_query = $wp_the_query;
or even better we can call:
wp_reset_query();
Everything other Chip outlined stays. After that query-reset-part you can call the pagination functions that are
f($wp_query)
, — they depend on$wp_query
global.
In order to further improve the pagination mechanics and to give more freedom to the
query_posts
function I created this possible improvement: -
- 2018-03-06
global $wp_query; $paged = get_query_var('paged', 1); $args = array( 'post_type' => '{your_post_type_name}', 'meta_query' => array('{add your meta query argument if need}'), 'orderby' => 'modified', 'order' => 'DESC', 'posts_per_page' => 20, 'paged' => $paged ); $query = new WP_Query($args); if($query->have_posts()): while ($query->have_posts()) : $query->the_post(); //add your code here endwhile; wp_reset_query(); //manage pagination based on custom Query. $GLOBALS['wp_query']->max_num_pages = $query->max_num_pages; the_posts_pagination(array( 'mid_size' => 1, 'prev_text' => __('Previous page', 'patelextensions'), 'next_text' => __('Next page', 'patelextensions'), 'before_page_number' => '<span class="meta-nav screen-reader-text">' . __('Page', 'patelextensions') . ' </span>', )); else: ?> <div class="container text-center"><?php echo _d('Result not found','30'); ?></div> <?php endif; ?>
global $wp_query; $paged = get_query_var('paged', 1); $args = array( 'post_type' => '{your_post_type_name}', 'meta_query' => array('{add your meta query argument if need}'), 'orderby' => 'modified', 'order' => 'DESC', 'posts_per_page' => 20, 'paged' => $paged ); $query = new WP_Query($args); if($query->have_posts()): while ($query->have_posts()) : $query->the_post(); //add your code here endwhile; wp_reset_query(); //manage pagination based on custom Query. $GLOBALS['wp_query']->max_num_pages = $query->max_num_pages; the_posts_pagination(array( 'mid_size' => 1, 'prev_text' => __('Previous page', 'patelextensions'), 'next_text' => __('Next page', 'patelextensions'), 'before_page_number' => '<span class="meta-nav screen-reader-text">' . __('Page', 'patelextensions') . ' </span>', )); else: ?> <div class="container text-center"><?php echo _d('Result not found','30'); ?></div> <?php endif; ?>
J'ai ajouté une requêtepersonnalisée/secondaire à unfichier demodèle/modèle depagepersonnalisé;Commentpuis-jefaireen sorte que WordPress utilisema requêtepersonnaliséepour lapagination,au lieu d'utiliser lapagination de laboucle de requêteprincipale?
Addendum
J'aimodifié la requête de laboucleprincipale via
query_posts()
.Pourquoi lapaginationne fonctionne-t-ellepaset comment y remédier?