Advertisement
helgatheviki

WordPress Block Context inheritance

Jan 9th, 2025 (edited)
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.95 KB | None | 0 0
  1. add_filter( 'render_block_context', function( $context, $parsed_block ) {
  2.     if ( 'core/query' === $parsed_block['blockName'] ) {
  3.         $context['helga/tacos'] = 'we love tacos';
  4.     }
  5.     return $context;
  6. }, 10, 2 );
  7.  
  8. add_filter( 'block_type_metadata', function( $metadata ) {
  9.     if ( 'core/query' === $metadata['name'] ) {
  10.         $metadata['attributes'] ??= [];
  11.         $metadata['attributes']['tacos'] = [
  12.             'type' => 'string',
  13.             'default' => 'default tacos',
  14.         ];
  15.  
  16.         $metadata['providesContext'] ??= [];
  17.         $metadata['providesContext']['helga/tacos'] = 'tacos';
  18.     }
  19.     if ( 'core/post-title' === $metadata['name'] ) {
  20.         $metadata['usesContext'] ??= [];
  21.         $metadata['usesContext'][] = 'helga/tacos';
  22.     }
  23.     return $metadata;
  24. } );
  25.  
  26. add_filter( 'render_block_core/post-title', function( $block_content, $block, $instance) {
  27.     $context = $instance->context['helga/tacos'] ?? 'no tacos'; // This is never set.
  28.     return '<p>context $taco: ' . $context . '</p>';
  29. }, 10, 3 );
  30.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement