Created
October 22, 2020 15:58
-
-
Save jasonbahl/fb7e5defa9cbd86154326b5347c2f7f1 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() { | |
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 ); | |
// Get the query amount from the resolver. | |
// This takes into account the arguments for `first` and `last` on the connection | |
// and determines how many items to ask for | |
$per_page = $resolver->get_query_amount(); | |
// Query for the popular posts. It's important to JUST get the ids | |
$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', // <-- Just ask for the IDs. WPGraphQL connection resolver will get the full objects for you | |
'no_found_rows' => true, | |
] ); | |
// If there are no popular posts, return null for the connection | |
if ( empty( $popular_post_ids->posts ) ) { | |
return null; | |
} | |
$resolver->set_query_arg( 'post__in', $popular_post_ids->posts ); | |
return $resolver->get_connection(); | |
} | |
]); | |
} ); |
Author
jasonbahl
commented
Oct 22, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment