Query post view
#1860
-
hi, is there anyway help us query post view count? I mean number of view for a post. |
Beta Was this translation helpful? Give feedback.
Answered by
jasonbahl
Dec 10, 2021
Replies: 1 comment 7 replies
-
@IRediTOTO I know I'm a bit late to responding here, but if you store the "view count" as post meta as described in the article, you should be able to register a field to the GraphQL Schema that can resolve that value. If you want the field to exist only on one post type, such as the "post" post type, you could register the field like so: add_action( 'graphql_register_types', function() {
register_graphql_field( 'Post', 'viewCount', [
'type' => 'Int',
'description' => __( 'The number of times the post was viewed', 'your-textdomain' ),
'resolve' => function( $post, $args, $context, $info ) {
// $post is an instance of a WPGraphQL Post model,
// so we can get the ID from the post, and then get meta from that post
// by calling get_post_meta()
$view_count = get_post_meta( $post->databaseId, 'post_views_count', true );
// if there's any count value, return it, otherwise return 0
return isset( $view_count ) ? absint( $view_count ) : 0;
}
]);
}); We can see this snippet of code in action using GraphiQL here: |
Beta Was this translation helpful? Give feedback.
7 replies
Answer selected by
jasonbahl
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@IRediTOTO I know I'm a bit late to responding here, but if you store the "view count" as post meta as described in the article, you should be able to register a field to the GraphQL Schema that can resolve that value.
If you want the field to exist only on one post type, such as the "post" post type, you could register the field like so: