Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Created September 20, 2022 00:28
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 lightningspirit/a316117fbb9294da0d15f57553875033 to your computer and use it in GitHub Desktop.
Save lightningspirit/a316117fbb9294da0d15f57553875033 to your computer and use it in GitHub Desktop.
Includes a `readingTime` field in seconds for every `Post` object response.

WPGraphQL Post Reading Time

Includes a readingTime field in seconds for every Post object response.

Usage

  1. Download this ZIP
  2. Upload to plugins
  3. Activate it
<?php
/**
* Plugin Name: WPGraphQL Post Reading Time
* Plugin URI: https://gist.github.com/lightningspirit/a316117fbb9294da0d15f57553875033
* Description: Includes a `readingTime` field in seconds for every `Post` object response.
* Author: Move Your Digital, Inc.
* Author URI: https://moveyourdigital.com
* Version: 0.1.0
*
* @package WPGraphQL_Post_Reading_Time
*/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// If this file is called directly, abort.
if (!defined('WPINC')) {
die;
}
add_action('graphql_register_types', function () {
register_graphql_fields(
'Post',
[
'readingTime' => [
'description' => __('Estimated post reading time', 'contasconnosco'),
'type' => 'int',
'resolve' => function (WPGraphQL\Model\Post $post) {
$word_count = str_word_count(strip_tags($post->contentRendered));
return ceil($word_count / 300);
},
],
],
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment