No Description

query-pagination-next.php 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/query-pagination-next` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/query-pagination-next` block on the server.
  9. *
  10. * @param array $attributes Block attributes.
  11. * @param string $content Block default content.
  12. * @param WP_Block $block Block instance.
  13. *
  14. * @return string Returns the next posts link for the query pagination.
  15. */
  16. function render_block_core_query_pagination_next( $attributes, $content, $block ) {
  17. $page_key = isset( $block->context['queryId'] ) ? 'query-' . $block->context['queryId'] . '-page' : 'query-page';
  18. $page = empty( $_GET[ $page_key ] ) ? 1 : (int) $_GET[ $page_key ];
  19. $max_page = isset( $block->context['query']['pages'] ) ? (int) $block->context['query']['pages'] : 0;
  20. $wrapper_attributes = get_block_wrapper_attributes();
  21. $default_label = __( 'Next Page &raquo;' );
  22. $label = isset( $attributes['label'] ) && ! empty( $attributes['label'] ) ? $attributes['label'] : $default_label;
  23. $content = '';
  24. // Check if the pagination is for Query that inherits the global context.
  25. if ( isset( $block->context['query']['inherit'] ) && $block->context['query']['inherit'] ) {
  26. $filter_link_attributes = function() use ( $wrapper_attributes ) {
  27. return $wrapper_attributes;
  28. };
  29. add_filter( 'next_posts_link_attributes', $filter_link_attributes );
  30. // Take into account if we have set a bigger `max page`
  31. // than what the query has.
  32. global $wp_query;
  33. if ( $max_page > $wp_query->max_num_pages ) {
  34. $max_page = $wp_query->max_num_pages;
  35. }
  36. $content = get_next_posts_link( $label, $max_page );
  37. remove_filter( 'next_posts_link_attributes', $filter_link_attributes );
  38. } elseif ( ! $max_page || $max_page > $page ) {
  39. $custom_query = new WP_Query( build_query_vars_from_query_block( $block, $page ) );
  40. if ( (int) $custom_query->max_num_pages !== $page ) {
  41. $content = sprintf(
  42. '<a href="%1$s" %2$s>%3$s</a>',
  43. esc_url( add_query_arg( $page_key, $page + 1 ) ),
  44. $wrapper_attributes,
  45. $label
  46. );
  47. }
  48. wp_reset_postdata(); // Restore original Post Data.
  49. }
  50. return $content;
  51. }
  52. /**
  53. * Registers the `core/query-pagination-next` block on the server.
  54. */
  55. function register_block_core_query_pagination_next() {
  56. register_block_type_from_metadata(
  57. __DIR__ . '/query-pagination-next',
  58. array(
  59. 'render_callback' => 'render_block_core_query_pagination_next',
  60. )
  61. );
  62. }
  63. add_action( 'init', 'register_block_core_query_pagination_next' );