如何获取WordPress分页文章的下一页链接(非自动输出)
Great question! I’ve run into this exact scenario before when customizing paginated posts (the ones split with <!--nextpage-->) in WordPress.
The Quickest Fix: Use wp_link_pages() Itself
You might not know this, but wp_link_pages() actually supports returning its output as a variable instead of printing it directly—just set the echo parameter to false! This is the most straightforward solution since it’s purpose-built for single-post pagination and handles all the logic of detecting your <!--nextpage--> splits automatically.
Here’s a practical example:
// Grab the pagination HTML as a variable instead of outputting it $paginated_links = wp_link_pages( array( 'echo' => false, 'before' => '<div class="post-pagination">', 'after' => '</div>', 'next_or_number'=> 'number', // Swap to 'next' to only show prev/next links 'nextpagelink' => 'Next Page', 'previouspagelink' => 'Previous Page' ) ); // Now you can manipulate or output the links however you want if ( $paginated_links ) { echo '<div class="custom-styled-pagination">' . $paginated_links . '</div>'; }
For Full Custom Control: Use paginate_links()
If you need granular control over every part of the pagination (like custom HTML for each page link, or adjusting URL structures), you can use paginate_links(). You’ll just need to pass in parameters specific to your single post’s pagination:
global $page, $numpages; // Only generate links if the post has multiple pages if ( $numpages > 1 ) { $custom_pagination = paginate_links( array( 'base' => get_permalink() . '%_%', 'format' => 'page/%#%/', // Matches WordPress's default single-post pagination URL structure 'current' => max( 1, $page ), 'total' => $numpages, 'echo' => false, 'prev_text' => '← Previous', 'next_text' => 'Next →' ) ); // Process and output the custom links if ( $custom_pagination ) { echo '<nav class="custom-post-pagination">' . $custom_pagination . '</nav>'; } }
Quick Comparison
wp_link_pages(): Low-effort, purpose-built for single-post pagination, handles<!--nextpage-->detection automatically.paginate_links(): Maximum flexibility, lets you fully customize every aspect of the pagination UI, but requires manual setup of pagination parameters.
内容的提问来源于stack exchange,提问作者albrox

