Querying Sticky Posts with GraphQL

Recently, a WPGraphQL user asked how to query only sticky posts with a GraphQL query. 

One of the great things about WPGraphQL is how customizable it is with hooks and filters, making it easy to extend the API for your needs. 

End goal

One (of many possible) solutions would be to allow the client to specify that they only want sticky posts as an argument on the posts connection query.

A query could look something like the following: 

query GET_STICKY_POSTS {
  posts( where: {onlySticky: true }) {
    nodes {
      id
      title
      date
      link
    }
  }
}

This query would allow the client to specify that they want posts, but onlySticky posts

This should give us what we were looking for, a way to query only sticky posts using WPGraphQL. 

The issue is that the onlySticky argument doesn’t exist in the WPGraphQL plugin, so if we want to use it, we’ll need to add it ourselves.

Register the “onlySticky” argument

To add this field as an argument, we can use the following snippet:

add_action( 'graphql_register_types', function() {
    register_graphql_field( 'RootQueryToPostConnectionWhereArgs', 'onlySticky', [
        'type' => 'Boolean',
        'description' => __( 'Whether to only include sticky posts', 'your-textdomain' ),
    ] );
} );

Here we hook into the graphql_register_types action, to make sure the GraphQL Type registry is ready to be hooked into. 

Next, we register a field to the GraphQL schema by using the register_graphql_field() method.

The first argument is the name of the Type to register the field to. In our case, that Type is RootQueryToPostConnectionWhereArgs. This is the Input Type that is used by the root posts field to provide filters to the query. 

The next argument is the name of the field we’re registering. Here, we’re using onlySticky as the field name. 

The third argument is an array to configure the field. We declare the Type the field should be is Boolean, meaning it should be either true or false, and provide a description for the field. 

At this point, our query would validate, as onlySticky would be a valid argument on the query now, but our actual results aren’t affected.

Filter the WP_Query to respect the onlySticky input

The next step we need to take is to filter how WPGraphQL resolves the query and make sure it respects the onlySticky argument that was input. 

We can do so with the following snippet:

add_filter( 'graphql_post_object_connection_query_args', function( $query_args, $source, $args, $context, $info ) {
    if ( isset( $args['where']['onlySticky'] ) && true === $args['where']['onlySticky'] ) {
        $sticky_ids = get_option( 'sticky_posts' );
        $query_args = [
            'posts_per_page' => count( $sticky_ids ),
            'post__in' => $sticky_ids
        ];
    }
    return $query_args;
}, 10, 5 );

Here, we filter graphql_post_object_connection_query_args. This filter can be found in the PostObjectConnectionResolver.php file in the WPGraphQL plugin. 

This allows for the $query_args that are prepared to send to WP_Query for execution to be filtered prior to WP_Query fetching the posts. 

Inside this filter, we check to see if the $args that were passed through the resolver from GraphQL include the onlySticky input, and if that value is true

If those conditions are met, then we define custom $query_args, by first getting a list of the sticky posts, then asking to query only those IDs and the posts_per_page equal to the number of sticky posts we have. 

Then we return the modified $query_args for WP_Query to use to resolve the query.

In action

Now, we can see our query in action. 

First, go set a couple posts to sticky, if you haven’t already:

Screenshot showing a few sticky posts

Then, using WPGraphiQL, execute the query, and the results returned should only be the Sticky posts!

GIF showing how the query with onlySticky set to true, and the results being only sticky posts

Conclusion

My hope is that this shows how easy it is to extend WPGraphQL for your system’s needs. The plugin is powerful out of the box, but if you have custom needs for your application, take advantage of the various hooks and filters in the plugin to make it work for you!

  1. Hey,

    Thanks for the article, it is really helpful!
    I think that I found 1 mistake in the query_args.
    Should be key ‘post__in’ instead of ‘p’.

    ‘p’ accepts single post ID (type Int).
    ‘post__in’ accepts an array of IDs
    and get_option( ‘sticky_posts’ ) returns an array

    reference – https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

    so should be:

    $query_args = [
    ‘posts_per_page’ => count( $sticky_ids ),
    ‘post__in’ => $sticky_ids
    ];

    1. Hey! Good catch. The actual demo code used to make the screen recording had post__in, not sure how it made it to the snippet as just ā€œpā€.

      Got it updated. šŸ˜€

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Introducing playground.wpgraphql.com

Introducing playground.wpgraphql.com