Tag: Posts

  • Showing Post Type labels in public queries

    WPGraphQL respects WordPress core access control rights. This means that data that is only available to authenticated users in the WordPress admin is only available to authenticated users making GraphQL requests.

    Sometimes, you want to expose fields that are restricted by default.

    Take the Post Type Label field, for example.

    Querying for the label of a Post Type as a public user returns a null value by default:

    Screenshot of a query for ContentTypes and their label, showing null value for the label.

    With the following snippet, you can expose the label field to public users:

    add_filter( 'graphql_allowed_fields_on_restricted_type', function( $allowed_restricted_fields, $model_name, $data, $visibility, $owner, $current_user ) {
    
    	if ( 'PostTypeObject' === $model_name ) {
    		$allowed_restricted_fields[] = 'label';
    	}
    
    	return $allowed_restricted_fields;
    
    }, 10, 6 );

    And below we can see the same query, showing the value of the labels to public users.

    Screenshot of a query for ContentTypes and their label, showing the label's value for the label.
  • Add Edit Link to All Post Types

    The following snippet shows how to add the “Edit” link as a GraphQL field to all post types:

    add_action( 'graphql_register_types', function() {
    
    	register_graphql_field( 'ContentNode', 'editLink', [
    		'type' => 'String',
    		'description' => __( 'Link to edit the content', 'your-textdomain' ),
    		'resolve' => function( \WPGraphQL\Model\Post $post, $args, $context, $info ) {
    		   return get_edit_post_link( $post->databaseId );
    		}
    	]);
    
    } );

    This could then be queried like so:

    Screenshot of a GraphQL Query for posts with their editLink
    Screenshot of a GraphQL Query for posts with their editLink