Using SNIP on Static Site Generators

Today I was asked by a customer if it’s possible to use schema generated by SNIP on static sites generators like Gatsby. The short answer to this is: not out of the box but in this article, I would like to give a few tips and assistance on how it can work after all.

Static Site Generators …

are super popular at this point in time. For me it makes totally sense to make some pages static as it’s faster and it saves a lot of energy on sites that do not show any dynamically generated data.

Now there is the question on how it’s possible to fetch the Structured Data generated by SNIP for pages that are generated statically.

A workaround for a single post, page or custom post type

As I wrote above, there is currently no official support for Gatsby and/or the GraphQL plugin. But with the following lines of code I’m sure a developer can fetch the necessary data! 😉

First of all you need to extend the Frontend_Controller class to accept the current post id that you’re querying.

class StaticSchemas extends \wpbuddy\rich_snippets\Frontend_Controller {

	public function __construct( $postId ) {
		$this->current_post_id = $postId;
		$this->caching = false;
	}
}

Normally, the comparison mechanism in SNIP compares the rules with the currently displayed post. I guess that in another environment there is no global query so we need to set it to the post needed.

add_filter( 'wpbuddy/rich_snippets/rule/query', function ( $query ) {
	return new WP_Query( [ 'p' => $theQueriedPost ] );
} );

Note: You may set $theQueriedPost to the right post ID. The filter is available in SNIP version 2.27.0.

And now make the magic happen. Here is the full code:

class StaticSchemas extends \wpbuddy\rich_snippets\Frontend_Controller {

	public function __construct( $postId ) {
		$this->current_post_id = $postId;
		$this->caching         = false;
	}
}

$queriedPost = 11;

add_filter( 'wpbuddy/rich_snippets/rule/query', function ( $query ) use ( $queriedPost ) {
	return new WP_Query( [ 'p' => $queriedPost ] );
} );

$staticSchemas = new StaticSchemas( $queriedPost );
$staticSchemas->print_snippets();

That’s it!