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