Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Last active November 26, 2024 12:51
Show Gist options
  • 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;
}
/**
* Get reading time for a post.
*
* @param \WP_Post|int $post The post object or ID.
* @return float The number of minutes
*/
function get_reading_time( \WP_Post|int $post ) {
$post = get_post( $post );
$post_content = get_the_content_plaintext( $post );
$word_count = str_word_count( $post_content );
$word_average = apply_filters( 'average_reading_words_per_minute', 300 );
$minutes = ceil( $word_count / $word_average );
return apply_filters( 'post_reading_time', $minutes, $post, $word_average );
}
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) {
return get_reading_time( $post );
},
],
],
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment