Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Created April 16, 2025 16:54
Show Gist options
  • Save jasonbahl/8a96f19d8f9a0c32103bfd4121957a97 to your computer and use it in GitHub Desktop.
Save jasonbahl/8a96f19d8f9a0c32103bfd4121957a97 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WPGraphQL Track GetText
* Description: Test plugin for tracking the number of times the wp-graphql textdomain is translated during a WPGraphQL request. The count is output in the "extensions" portion of the graphql response.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class TestGetText {
/**
* @var array
*/
protected $gettext_log = [];
/**
* Constructor
*/
public function __construct() {
// Reset at the very start of schema generation
add_action( 'graphql_process_http_request', [ $this, 'init_log' ], 1 );
// Track all translations
add_filter(
'gettext',
function ( $translation, $text, $domain ) {
if ( 'wp-graphql' === $domain ) {
$this->gettext_log[] = $text;
}
return $translation;
},
10,
3
);
// Add to extensions
add_filter( 'graphql_request_results', [ $this, 'add_to_extensions' ], 10, 1 );
}
/**
* Initialize the log
*/
public function init_log(): void {
$this->gettext_log = [];
}
/**
* Add translation data to GraphQL extensions
*
* @param \GraphQL\Executor\ExecutionResult $response The GraphQL response
*/
public function add_to_extensions( \GraphQL\Executor\ExecutionResult $response ): \GraphQL\Executor\ExecutionResult {
$extensions = $response->extensions ?? [];
$extensions['translations'] = [
'count' => count( $this->gettext_log ),
// 'log' => $this->gettext_log,
];
$response->extensions = $extensions;
return $response;
}
}
new TestGetText();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment