Created
December 10, 2018 22:06
-
-
Save jasonbahl/c80bd9999f75b97c619ac6faf834dc0d to your computer and use it in GitHub Desktop.
Adding a "likePost" mutation for WPGraphQL
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() { | |
register_graphql_field( 'Post', 'likeCount', [ | |
'type' => 'Int', | |
'description' => __( 'The number of likes for the post', 'your-textdomain' ), | |
'resolve' => function( $post ) { | |
$likes = get_post_meta( $post->ID, 'likes', true ); | |
return isset( $likes ) ? (int) $likes : 0; | |
} | |
] ); | |
register_graphql_mutation( 'likePost', [ | |
'inputFields' => [ | |
'id' => [ | |
'type' => [ | |
'non_null' => 'ID' | |
], | |
'description' => __( 'ID of the post to like', 'your-textdomain' ), | |
], | |
], | |
'outputFields' => [ | |
'post' => [ | |
'type' => 'Post', | |
'description' => __( 'The post that was liked', 'your-textdomain' ), | |
], | |
], | |
'mutateAndGetPayload' => function( $input ) { | |
$id = null; | |
if ( absint( $input['id'] ) ) { | |
$id = absint( $input['id'] ); | |
} else { | |
$id_parts = \GraphQLRelay\Relay::fromGlobalId( $input['id'] ); | |
if ( ! empty( $id_parts['id'] ) && absint( $id_parts['id'] ) ) { | |
$id = absint( $id_parts['id'] ); | |
} | |
} | |
/** | |
* If the ID is invalid or the post object doesn't exist, throw an error | |
*/ | |
if ( empty( $id ) || false == $post = get_post( absint( $id ) ) ) { | |
throw new \GraphQL\Error\UserError( __( 'The ID entered is invalid' ) ); | |
} | |
/** | |
* If you wanted to only allow certain users to "like" a post, you could do | |
* some capability checks here too, or whatever validation you want to apply. . . | |
*/ | |
$current_likes = (int) get_post_meta( $post->ID, 'likes', true ); | |
update_post_meta( $post->ID, 'likes', absint( $current_likes + 1 ) ); | |
return [ | |
'post' => $post | |
]; | |
} | |
] ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The GIST shows one approach to creating a "likePost" mutation that accepts an ID as input.
You can see what's possible in the GIF below