From de8ab396f9db1ce0c935a145a1524e61dc011170 Mon Sep 17 00:00:00 2001 From: Giulio Ganci Date: Fri, 3 Sep 2021 15:09:08 +0200 Subject: [PATCH] added offset pagination support to comments --- src/Loader.php | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/Loader.php b/src/Loader.php index 39a9f84..f273cbb 100644 --- a/src/Loader.php +++ b/src/Loader.php @@ -36,6 +36,13 @@ function bind_hooks() 2 ); + add_filter( + 'graphql_map_input_fields_to_wp_comment_query', + [$this, 'op_filter_map_offset_to_wp_comment_query_args'], + 10, + 2 + ); + add_filter( 'graphql_connection_page_info', [$this, 'op_filter_graphql_connection_page_info'], @@ -135,6 +142,8 @@ function op_filter_graphql_connection_page_info( $total = $query->found_posts; } elseif ($query instanceof \WP_User_Query) { $total = $query->total_users; + } else if($query instanceof \WP_Comment_Query) { + $total = $query->found_comments; } $page_info['offsetPagination'] = [ @@ -179,12 +188,38 @@ function op_filter_map_offset_to_wp_user_query_args( return $query_args; } + function op_filter_map_offset_to_wp_comment_query_args( + $query_args, + $where_args + ) { + if ( isset( $where_args['offsetPagination']['offset'] ) ) { + $query_args['offset'] = $where_args['offsetPagination']['offset']; + } + + if ( isset( $where_args['offsetPagination']['size'] ) ) { + $query_args['posts_per_page'] = + intval( $where_args['offsetPagination']['size'] ) + 1; + } + + return $query_args; + } + function op_action_register_types() { foreach (\WPGraphQL::get_allowed_post_types() as $post_type) { self::add_post_type_fields(get_post_type_object($post_type)); } + register_graphql_fields('RootQueryToCommentConnectionWhereArgs', [ + 'offsetPagination' => [ + 'type' => 'OffsetPagination', + 'description' => __( + 'Paginate Comments with offsets', + 'wp-graphql-offset-pagination' + ), + ], + ]); + register_graphql_object_type('OffsetPaginationPageInfo', [ 'description' => __( 'Get information about the offset pagination state',