add_action( 'graphql_register_types', function() {
register_graphql_connection([
'fromType' => 'RootQuery',
'toType' => 'Post',
'fromFieldName' => 'popularPosts',
'connectionTypeName' => 'RootQueryToPopularPostsConnection',
'resolve' => function( $root, $args, \WPGraphQL\AppContext $context, $info ) {
$resolver = new \WPGraphQL\Data\Connection\PostObjectConnectionResolver( $root, $args, $context, $info );
$per_page = $resolver->get_query_amount();
$popular_post_ids = new WP_Query( [
'posts_per_page' => $per_page,
'meta_key' => 'wpb_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'fields' => 'ids',
'no_found_rows' => true,
] );
if ( empty( $popular_post_ids->posts ) ) {
return null;
}
$resolver->set_query_arg( 'post__in', $popular_post_ids->posts );
return $resolver->get_connection();
}
]);
} );