Skip To Main Content

wp-graphql-content-blocks filters

Sometimes you want to change or add new types of block attributes that you want exposed in the WPGraphQL API. This can be accomplished by using the wpgraphql_content_blocks_block_class filter available to you in the wp-graphql-content-blocks plugin.

wpgraphql_content_blocks_block_class

This filter allows you to provide a new type that inherits the WPGraphQL\ContentBlocks\Blocks\Block class and allows you to use that class instead for registering new WPGraphQL fields.

Here is an example of the wpgraphql_content_blocks_block_class filter in action:

// We include the type of Block class
include_once plugin_dir_path( __DIR__ ) . 'wp-graphql-content-blocks/includes/Blocks/Block.php';

// We register the filter here
add_filter( 'wpgraphql_content_blocks_block_class', 'custom_graphql_editor_block_init', 10, 3 );

// We provide the filter implementation here
function custom_graphql_editor_block_init($class_name, $block, $self) {
    if (str_ends_with($class_name, "CreateBlockMyFirstBlock")) {
        return MyFirstBlock::class;
    }
    return $class_name;
}
// We define class of the MyFirstBlock that inherits from the Block class
class MyFirstBlock extends WPGraphQL\ContentBlocks\Blocks\Block {}
Code language: PHP (php)

The class MyFirstBlock needs to inherit from WPGraphQL\ContentBlocks\Blocks\Block as the parent class performs certain background work to register this block with WPGraphQL.

To customize the parent class:

Using the additional_block_attributes property: Use additional block attributes for a block by defining a property additional_block_attributes on your extending class. This property is of type array and you can assign the list of attributes as key-value pairs similar to the block.json attributes spec:

class MyFirstBlock extends WPGraphQL\ContentBlocks\Blocks\Block
{
    protected ?array $additional_block_attributes = array(
      'align' => array(
        'type' => 'string',
        'default' => 'left',
      )
    );
}
Code language: PHP (php)

If the structure is correct you will be able to query the new align attribute:

{
  posts {
    nodes {
      editorBlocks {
        ... on CreateBlockMyFirstBlock {
          name
          attributes {
            align
          }
        }
      }
    }
  }
}

The structure of the block attributes needs to follow the attributes guide. For example, the structure of this attribute is:

url: {
  type: 'string',
  source: 'attribute',
  selector: 'img',
  attribute: 'src',
},Code language: CSS (css)

This needs to be converted to:

'url' => array(
  'type' => 'string',
  'source' => 'attribute',
  'selector' => 'img',
  'attribute' => 'src',
)
Code language: PHP (php)