query-pagination-previous.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/query-pagination-previous` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/query-pagination-previous` 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 previous posts link for the query.
  15. */
  16. function render_block_core_query_pagination_previous( $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. $wrapper_attributes = get_block_wrapper_attributes();
  20. $default_label = __( 'Previous Page' );
  21. $label = isset( $attributes['label'] ) && ! empty( $attributes['label'] ) ? esc_html( $attributes['label'] ) : $default_label;
  22. $pagination_arrow = get_query_pagination_arrow( $block, false );
  23. if ( $pagination_arrow ) {
  24. $label = $pagination_arrow . $label;
  25. }
  26. $content = '';
  27. // Check if the pagination is for Query that inherits the global context
  28. // and handle appropriately.
  29. if ( isset( $block->context['query']['inherit'] ) && $block->context['query']['inherit'] ) {
  30. $filter_link_attributes = function() use ( $wrapper_attributes ) {
  31. return $wrapper_attributes;
  32. };
  33. add_filter( 'previous_posts_link_attributes', $filter_link_attributes );
  34. $content = get_previous_posts_link( $label );
  35. remove_filter( 'previous_posts_link_attributes', $filter_link_attributes );
  36. } elseif ( 1 !== $page ) {
  37. $content = sprintf(
  38. '<a href="%1$s" %2$s>%3$s</a>',
  39. esc_url( add_query_arg( $page_key, $page - 1 ) ),
  40. $wrapper_attributes,
  41. $label
  42. );
  43. }
  44. return $content;
  45. }
  46. /**
  47. * Registers the `core/query-pagination-previous` block on the server.
  48. */
  49. function register_block_core_query_pagination_previous() {
  50. register_block_type_from_metadata(
  51. __DIR__ . '/query-pagination-previous',
  52. array(
  53. 'render_callback' => 'render_block_core_query_pagination_previous',
  54. )
  55. );
  56. }
  57. add_action( 'init', 'register_block_core_query_pagination_previous' );