Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Last active September 26, 2022 15:50
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/2334e1fcc2ca05508e868b39fc559e7a to your computer and use it in GitHub Desktop.
Save lightningspirit/2334e1fcc2ca05508e868b39fc559e7a to your computer and use it in GitHub Desktop.
WPGraphQL add field format plain text

WPGraphQL add field format plain text

This small plugin adds a new format to retrieve excerpt or title in text plain format instead of rendered.

Usage

  1. Install WPGraphQL
  2. Download or copy the wpgraphql-field-format-text-plain.php file
  3. Place it under wp-content/mu-plugins
  4. 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment