-
Notifications
You must be signed in to change notification settings - Fork 5
/
pagination-fields.php
91 lines (77 loc) · 3.18 KB
/
pagination-fields.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
use WP_Post;
use WPGraphQL\Model\Post;
class PaginationFields {
public function register_hooks() {
add_action( 'graphql_register_types', [ $this, 'register_post_fields' ] );
}
public function register_post_fields() {
register_graphql_fields('Post', [
'previousPost' => [
'type' => 'Post',
'description' => __( 'Previous post', 'hwp-rockers' ),
'resolve' => function( Post $resolving_post ) {
if ( is_post_type_hierarchical( $resolving_post->post_type ) ) {
$previous_post_id = get_previous_page_id( $resolving_post );
return $previous_post_id ? new Post( $previous_post_id ) : null;
}
$post = get_post( $resolving_post->postId );
$GLOBALS['post'] = $post;
setup_postdata( $post );
$previous_post = get_previous_post();
wp_reset_postdata();
return $previous_post ? new Post( $previous_post ) : null;
}
],
'nextPost' => [
'type' => 'Post',
'description' => __( 'Next post', 'hwp-rockers' ),
'resolve' => function( Post $resolving_post ) {
if ( is_post_type_hierarchical( $resolving_post->post_type ) ) {
$next_post_id = get_next_page_id( $resolving_post );
return $next_post_id ? new Post( $next_post_id ) : null;
}
$post = get_post( $resolving_post->postId );
$GLOBALS['post'] = $post;
setup_postdata( $post );
$next_post = get_next_post();
wp_reset_postdata();
return $next_post ? new Post( $next_post ) : null;
}
],
]);
}
private function get_previous_page_id( Post $page ): int {
return get_adjacent_page_id( $page, -1 );
}
private function get_next_page_id( Post $page ): int {
return get_adjacent_page_id( $page, 1 );
}
/*
* @param WP_Post $page Page Object.
* @param int $direction Integer -1 or 1 indicating next or previous post.
*
* @return int Adjacent page id, or 0 if none.
*/
private function get_adjacent_page_id( WP_Post $page, int $direction ): int {
$args = [
'post_type' => $page->post_type,
'order' => 'ASC',
'orderby' => 'menu_order',
'post_parent' => $page->post_parent,
'fields' => 'ids',
'posts_per_page' => -1
];
$pages = get_posts( $args );
$current_key = array_search( $page->ID, $pages );
$does_adjacent_page_exist = isset( $pages[ $current_key + $direction ] );
if ( $does_adjacent_page_exist ) {
return $pages[ $current_key + $direction ];
}
return 0;
}
}
add_action( 'plugins_loaded', function() {
$pagination_fields = new PaginationFields();
$pagination_fields->register_hooks();
} );