Skip to main content

Custom fields

Advanced Custom Fields provides a convenient and flexible way to add fields to all entities.

For example, let's add a boolean field to Category.

use StoutLogic\AcfBuilder\FieldsBuilder;
add_action(
'acf/init',
function () {
$builder = new FieldsBuilder( 'Group name', [ 'position' => 'side' ] );
$builder->addTrueFalse(
'field_name',
[
'label' => 'Field title',
]
)->setLocation( 'taxonomy', '==', 'category' );
acf_add_local_field_group( $builder->build() );
}
);

ACF fields expose to the Graphql API automatically. The data will be available by graphql query.

{
resolveUrl(url: "/url/to/category") {
node {
... on Category {
groupName {
fieldName
}
}
}
}
}

To make the field private, use 'show_in_graphql' => false, option.

See also:

Other meta fields and custom resolvers

The custom resolver must be used to expose other meta fields or computed fields.

        add_action( 'graphql_register_types', function () {
register_graphql_field(
'Post', // Root type
'fieldName', // Field name
[
'type' => 'String', // Field type
'resolve' => function(\WPGraphQL\Model\Post $post) {
return get_post_meta( $post->ID, 'custom_meta_key', true );
},
]
);
}, 10, 1 );

The new field is available by query:

{
resolveUrl(url: "/url/to/post") {
node {
... on Post {
fieldName
}
}
}
}

See also

Frontend

Fetch

Run command yarn graphql:fetch to pull updated schema.

Add field to query fragment

Add fragment for custom options fields

  • for Post use one of the next fragments;
    • postDetailsFragment.ts
    • postFragment.ts
    • categoryPostFragment.ts
  • for Category use one of the next fragments;
    • categoryLinkFragment.ts - for all categories;
    • categoryPrimaryFragment.ts - for primary category;
    • categoryFullFragment.ts - for category pages;
  • for Author
    • authorPageFragments.ts - for Author pages;
    • authorTagsNodeFragment.ts - for authors on other pages;
  • for Page use pageDetailsFragment.ts;
  • for Tag use tagFullFragment.ts

Codegen

Run command yarn graphql:codegen to generate types based on queries.

For newly created GQL fields (like those belonging to custom blocks), you will also need to run yarn graphql:fetch.