Created
October 25, 2020 08:43
-
-
Save izzygld/a4f1eec2fb49565c89bf6b898f6fda2c to your computer and use it in GitHub Desktop.
wp-graphql-popular-posts-connection.php
This file contains hidden or 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(); | |
} | |
]); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
are you sure this code works well?
I can't find sth for showing popular-posts with wpgraphql.