Includes a readingTime
field in seconds for every Post
object response.
- Download this ZIP
- Upload to plugins
- 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); | |
}, | |
], | |
], | |
); | |
}); |