Using WordPress ‘block_parser_class’ PHP filter

The block_parser_class WordPress PHP filter allows plugins to replace the server-side block parser.

Usage

add_filter('block_parser_class', 'your_custom_parser_class');

function your_custom_parser_class($parser_class) {
    // your custom code here
    return $parser_class;
}

Parameters

  • $parser_class: string. Name of block parser class.

More information

See WordPress Developer Resources: block_parser_class

Examples

Replacing the default block parser with a custom parser

This example replaces the default block parser with a custom parser called My_Custom_Block_Parser.

add_filter('block_parser_class', 'use_my_custom_block_parser');

function use_my_custom_block_parser($parser_class) {
    return 'My_Custom_Block_Parser';
}

Using a namespaced custom block parser

This example demonstrates how to use a namespaced custom block parser.

add_filter('block_parser_class', 'use_namespaced_custom_parser');

function use_namespaced_custom_parser($parser_class) {
    return 'MyNamespace\\CustomBlockParser';
}

Conditionally replacing the block parser

This example shows how to conditionally replace the block parser based on a certain condition (e.g., a user role).

add_filter('block_parser_class', 'conditionally_replace_block_parser');

function conditionally_replace_block_parser($parser_class) {
    if (current_user_can('edit_posts')) {
        return 'My_Editors_Block_Parser';
    }
    return $parser_class;
}

Replacing the block parser for a specific post type

This example demonstrates how to replace the block parser only for a specific post type.

add_filter('block_parser_class', 'replace_block_parser_for_post_type', 10, 2);

function replace_block_parser_for_post_type($parser_class, $post_type) {
    if ($post_type == 'my_custom_post_type') {
        return 'My_Custom_Post_Type_Block_Parser';
    }
    return $parser_class;
}

Using an external class as the block parser

This example shows how to use an external class from a third-party library as the block parser.

add_filter('block_parser_class', 'use_external_block_parser');

function use_external_block_parser($parser_class) {
    return 'ThirdPartyLibrary\\ExternalBlockParser';
}