Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Last active January 3, 2023 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbahl/d777c7229bad5142211a58ed00da6598 to your computer and use it in GitHub Desktop.
Save jasonbahl/d777c7229bad5142211a58ed00da6598 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WPGraphQL Smart Cache for Litespeed
* Description: Allows WPGraphQL Smart Cache to work for WordPress sites hosted on environments using Litespeed Cache
* Author: WPGraphQL
* Author URI: http://www.wpgraphql.com
* Text Domain: wp-graphql-smart-cache-litespeed
* Version: 0.0.1
* Requires at least: 5.0
* Tested up to: 6.1
* Requires PHP: 7.1
* License: GPL-3
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/
// Initialize the bridge between wpgraphql smart cache and litespeed cache
add_action( 'plugins_loaded', 'graphql_smart_cache_litespeed_init' );
/**
* Initialize the bridge between wpgraphql smart cache and litespeed cache
*/
function graphql_smart_cache_litespeed_init() {
// if the litespeed cache plugin isn't active, do nothing
if ( ! defined( 'LSCWP_V' ) ) {
return;
}
// force litespeed to cache GraphQL queries made over GET requests
add_action( 'graphql_process_http_request_response', 'graphql_litespeed_force_cacheable' );
// add litespeed tags, unset the x-graphql-keys
add_filter( 'graphql_response_headers_to_send', 'graphql_litespeed_tag_responses' );
// call litespeed_purge when graphql_purge is called
add_action( 'graphql_purge', 'graphql_litespeed_purge' );
}
/**
* Force GraphQL Queries returned via HTTP GET requests to be cacheable
*/
function graphql_litespeed_force_cacheable() {
if ( 'GET' !== $_SERVER['REQUEST_METHOD'] ) {
return;
}
do_action( 'litespeed_control_force_cacheable' );
}
/**
* add litespeed tags, unset the x-graphql-keys
*
* @param array
*
* @return array
*/
function graphql_litespeed_tag_responses( array $headers = [] ): array {
if ( isset( $headers['X-GraphQL-Keys'] ) ) {
do_action( 'litespeed_tag_add', explode( ' ', $headers['X-GraphQL-Keys'] ) );
// unset the x-graphql-keys headers so that we don't overpopulate the headers as there are header size limitations
unset( $headers['X-GraphQL-Keys'] );
}
return $headers;
}
/**
* call litespeed_purge when graphql_purge is called
*
* @param string|array
*
* @return void
*/
function graphql_litespeed_purge( $keys ) {
do_action( 'litespeed_purge', $keys );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment