This small plugin adds a new format to retrieve excerpt or title in text plain format instead of rendered.
- Install WPGraphQL
- Download or copy the
wpgraphql-field-format-text-plain.phpfile - Place it under
wp-content/mu-plugins - Done
| <?php | |
| /** | |
| * Plugin Name: WPGraphQL Plain Text Field Format | |
| * Plugin URI: https://gist.github.com/lightningspirit/2334e1fcc2ca05508e868b39fc559e7a | |
| * Author: Move Your Digital, Inc. | |
| * Author URI: https://moveyourdigital.com | |
| * Version: 0.1.0 | |
| * | |
| * @package WPGraphQL_Plain_Text_Field_Format | |
| */ | |
| /* | |
| 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 | |
| */ | |
| use GraphQL\Type\Definition\FieldDefinition; | |
| use GraphQL\Type\Definition\ResolveInfo; | |
| use WPGraphQL\AppContext; | |
| /** | |
| * | |
| */ | |
| add_filter('graphql_PostObjectFieldFormatEnum_values', function ($values) { | |
| $values['TEXT_PLAIN'] = [ | |
| 'value' => 'text_plain', | |
| 'description' => __('Provide the field in text/plain format', 'wp-graphql'), | |
| ]; | |
| return $values; | |
| }); | |
| /** | |
| * | |
| */ | |
| add_filter('graphql_pre_resolve_field', function ($nil, $source, array $args, AppContext $context, ResolveInfo $info, string $type_name, string $field_key, FieldDefinition $field, $field_resolver) { | |
| if (!in_array($field_key, ['excerpt', 'title'])) { | |
| return $nil; | |
| } | |
| if (isset($args['format']) && $args['format'] != "text_plain") { | |
| return $nil; | |
| } | |
| $value = $source->{"${field_key}Rendered"}; | |
| if ($value) { | |
| return wp_strip_all_tags($value); | |
| } | |
| return $nil; | |
| }, 10, 9); |