Created
April 9, 2019 19:06
-
-
Save jasonbahl/55a6eff4cd67ce639ecd2d9989fef4cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'graphql_register_types', function() { | |
$post_types = WPGraphQL::$allowed_post_types; | |
if ( ! empty( $post_types ) && is_array( $post_types ) ) { | |
foreach ( $post_types as $post_type ) { | |
$post_type_object = get_post_type_object( $post_type ); | |
/** | |
* Get the Type name with ucfirst | |
*/ | |
$ucfirst = ucfirst( $post_type_object->graphql_single_name ); | |
/** | |
* Register a new Edge Type | |
*/ | |
register_graphql_type( 'Next' . $ucfirst . 'Edge', [ | |
'fields' => [ | |
'node' => [ | |
'description' => __( 'The node of the next item', 'wp-graphql' ), | |
'type' => $ucfirst, | |
], | |
], | |
] ); | |
/** | |
* Register the next{$type} field | |
*/ | |
register_graphql_field( $ucfirst, 'next' . $ucfirst, [ | |
'type' => 'Next' . $ucfirst . 'Edge', | |
'description' => __( 'The next post of the current port', 'wp-graphql' ), | |
'resolve' => function( $resolving_post, $args, $context ) { | |
$resolving_post = get_post( $resolving_post->postId ); | |
$GLOBALS['post'] = $resolving_post; | |
setup_postdata( $resolving_post ); | |
$nextPost = get_next_post(); | |
$post_model = $nextPost ? new \WPGraphQL\Model\Post( $nextPost ) : null; | |
$result = [ | |
'node' => ! empty( $post_model ) ? $post_model : null, | |
]; | |
return empty( $nextPost ) ? null : $result; | |
} | |
] ); | |
/** | |
* Register a new Edge Type | |
*/ | |
register_graphql_type( 'Previous' . $ucfirst . 'Edge', [ | |
'fields' => [ | |
'node' => [ | |
'description' => __( 'The node of the previous item', 'wp-graphql' ), | |
'type' => $ucfirst, | |
], | |
], | |
] ); | |
/** | |
* Register the next{$type} field | |
*/ | |
register_graphql_field( $ucfirst, 'previous' . $ucfirst, [ | |
'type' => 'Previous' . $ucfirst . 'Edge', | |
'description' => __( 'The previous post of the current port', 'wp-graphql' ), | |
'resolve' => function( $resolving_post, $args, $context ) { | |
$resolving_post = get_post( $resolving_post->postId ); | |
$GLOBALS['post'] = $resolving_post; | |
setup_postdata( $resolving_post ); | |
$nextPost = get_previous_post(); | |
$post_model = $nextPost ? new \WPGraphQL\Model\Post( $nextPost ) : null; | |
$result = [ | |
'node' => ! empty( $post_model ) ? $post_model : null, | |
]; | |
return empty( $nextPost ) ? null : $result; | |
} | |
] ); | |
} | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment