[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Functions related to registering and parsing blocks. 4 * 5 * @package WordPress 6 * @subpackage Blocks 7 * @since 5.0.0 8 */ 9 10 /** 11 * Removes the block asset's path prefix if provided. 12 * 13 * @since 5.5.0 14 * 15 * @param string $asset_handle_or_path Asset handle or prefixed path. 16 * @return string Path without the prefix or the original value. 17 */ 18 function remove_block_asset_path_prefix( $asset_handle_or_path ) { 19 $path_prefix = 'file:'; 20 if ( ! str_starts_with( $asset_handle_or_path, $path_prefix ) ) { 21 return $asset_handle_or_path; 22 } 23 $path = substr( 24 $asset_handle_or_path, 25 strlen( $path_prefix ) 26 ); 27 if ( str_starts_with( $path, './' ) ) { 28 $path = substr( $path, 2 ); 29 } 30 return $path; 31 } 32 33 /** 34 * Generates the name for an asset based on the name of the block 35 * and the field name provided. 36 * 37 * @since 5.5.0 38 * @since 6.1.0 Added `$index` parameter. 39 * 40 * @param string $block_name Name of the block. 41 * @param string $field_name Name of the metadata field. 42 * @param int $index Optional. Index of the asset when multiple items passed. 43 * Default 0. 44 * @return string Generated asset name for the block's field. 45 */ 46 function generate_block_asset_handle( $block_name, $field_name, $index = 0 ) { 47 if ( str_starts_with( $block_name, 'core/' ) ) { 48 $asset_handle = str_replace( 'core/', 'wp-block-', $block_name ); 49 if ( str_starts_with( $field_name, 'editor' ) ) { 50 $asset_handle .= '-editor'; 51 } 52 if ( str_starts_with( $field_name, 'view' ) ) { 53 $asset_handle .= '-view'; 54 } 55 if ( $index > 0 ) { 56 $asset_handle .= '-' . ( $index + 1 ); 57 } 58 return $asset_handle; 59 } 60 61 $field_mappings = array( 62 'editorScript' => 'editor-script', 63 'script' => 'script', 64 'viewScript' => 'view-script', 65 'editorStyle' => 'editor-style', 66 'style' => 'style', 67 ); 68 $asset_handle = str_replace( '/', '-', $block_name ) . 69 '-' . $field_mappings[ $field_name ]; 70 if ( $index > 0 ) { 71 $asset_handle .= '-' . ( $index + 1 ); 72 } 73 return $asset_handle; 74 } 75 76 /** 77 * Finds a script handle for the selected block metadata field. It detects 78 * when a path to file was provided and finds a corresponding asset file 79 * with details necessary to register the script under automatically 80 * generated handle name. It returns unprocessed script handle otherwise. 81 * 82 * @since 5.5.0 83 * @since 6.1.0 Added `$index` parameter. 84 * 85 * @param array $metadata Block metadata. 86 * @param string $field_name Field name to pick from metadata. 87 * @param int $index Optional. Index of the script to register when multiple items passed. 88 * Default 0. 89 * @return string|false Script handle provided directly or created through 90 * script's registration, or false on failure. 91 */ 92 function register_block_script_handle( $metadata, $field_name, $index = 0 ) { 93 if ( empty( $metadata[ $field_name ] ) ) { 94 return false; 95 } 96 97 $script_handle = $metadata[ $field_name ]; 98 if ( is_array( $script_handle ) ) { 99 if ( empty( $script_handle[ $index ] ) ) { 100 return false; 101 } 102 $script_handle = $script_handle[ $index ]; 103 } 104 105 $script_path = remove_block_asset_path_prefix( $script_handle ); 106 if ( $script_handle === $script_path ) { 107 return $script_handle; 108 } 109 110 $script_asset_raw_path = dirname( $metadata['file'] ) . '/' . substr_replace( $script_path, '.asset.php', - strlen( '.js' ) ); 111 $script_handle = generate_block_asset_handle( $metadata['name'], $field_name, $index ); 112 $script_asset_path = wp_normalize_path( 113 realpath( $script_asset_raw_path ) 114 ); 115 116 if ( empty( $script_asset_path ) ) { 117 _doing_it_wrong( 118 __FUNCTION__, 119 sprintf( 120 /* translators: 1: Asset file location, 2: Field name, 3: Block name. */ 121 __( 'The asset file (%1$s) for the "%2$s" defined in "%3$s" block definition is missing.' ), 122 $script_asset_raw_path, 123 $field_name, 124 $metadata['name'] 125 ), 126 '5.5.0' 127 ); 128 return false; 129 } 130 131 // Path needs to be normalized to work in Windows env. 132 static $wpinc_path_norm = ''; 133 if ( ! $wpinc_path_norm ) { 134 $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) ); 135 } 136 137 $theme_path_norm = wp_normalize_path( get_theme_file_path() ); 138 $script_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $script_path ) ); 139 140 $is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm ); 141 $is_theme_block = str_starts_with( $script_path_norm, $theme_path_norm ); 142 143 $script_uri = plugins_url( $script_path, $metadata['file'] ); 144 if ( $is_core_block ) { 145 $script_uri = includes_url( str_replace( $wpinc_path_norm, '', $script_path_norm ) ); 146 } elseif ( $is_theme_block ) { 147 $script_uri = get_theme_file_uri( str_replace( $theme_path_norm, '', $script_path_norm ) ); 148 } 149 150 $script_asset = require $script_asset_path; 151 $script_dependencies = isset( $script_asset['dependencies'] ) ? $script_asset['dependencies'] : array(); 152 $result = wp_register_script( 153 $script_handle, 154 $script_uri, 155 $script_dependencies, 156 isset( $script_asset['version'] ) ? $script_asset['version'] : false 157 ); 158 if ( ! $result ) { 159 return false; 160 } 161 162 if ( ! empty( $metadata['textdomain'] ) && in_array( 'wp-i18n', $script_dependencies, true ) ) { 163 wp_set_script_translations( $script_handle, $metadata['textdomain'] ); 164 } 165 166 return $script_handle; 167 } 168 169 /** 170 * Finds a style handle for the block metadata field. It detects when a path 171 * to file was provided and registers the style under automatically 172 * generated handle name. It returns unprocessed style handle otherwise. 173 * 174 * @since 5.5.0 175 * @since 6.1.0 Added `$index` parameter. 176 * 177 * @param array $metadata Block metadata. 178 * @param string $field_name Field name to pick from metadata. 179 * @param int $index Optional. Index of the style to register when multiple items passed. 180 * Default 0. 181 * @return string|false Style handle provided directly or created through 182 * style's registration, or false on failure. 183 */ 184 function register_block_style_handle( $metadata, $field_name, $index = 0 ) { 185 if ( empty( $metadata[ $field_name ] ) ) { 186 return false; 187 } 188 189 static $wpinc_path_norm = ''; 190 if ( ! $wpinc_path_norm ) { 191 $wpinc_path_norm = wp_normalize_path( realpath( ABSPATH . WPINC ) ); 192 } 193 194 $is_core_block = isset( $metadata['file'] ) && str_starts_with( $metadata['file'], $wpinc_path_norm ); 195 // Skip registering individual styles for each core block when a bundled version provided. 196 if ( $is_core_block && ! wp_should_load_separate_core_block_assets() ) { 197 return false; 198 } 199 200 $style_handle = $metadata[ $field_name ]; 201 if ( is_array( $style_handle ) ) { 202 if ( empty( $style_handle[ $index ] ) ) { 203 return false; 204 } 205 $style_handle = $style_handle[ $index ]; 206 } 207 208 $style_path = remove_block_asset_path_prefix( $style_handle ); 209 $is_style_handle = $style_handle === $style_path; 210 // Allow only passing style handles for core blocks. 211 if ( $is_core_block && ! $is_style_handle ) { 212 return false; 213 } 214 // Return the style handle unless it's the first item for every core block that requires special treatment. 215 if ( $is_style_handle && ! ( $is_core_block && 0 === $index ) ) { 216 return $style_handle; 217 } 218 219 // Check whether styles should have a ".min" suffix or not. 220 $suffix = SCRIPT_DEBUG ? '' : '.min'; 221 if ( $is_core_block ) { 222 $style_path = "style$suffix.css"; 223 } 224 225 $style_path_norm = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . $style_path ) ); 226 $has_style_file = '' !== $style_path_norm; 227 228 if ( $has_style_file ) { 229 $style_uri = plugins_url( $style_path, $metadata['file'] ); 230 231 // Cache $theme_path_norm to avoid calling get_theme_file_path() multiple times. 232 static $theme_path_norm = ''; 233 if ( ! $theme_path_norm ) { 234 $theme_path_norm = wp_normalize_path( get_theme_file_path() ); 235 } 236 237 $is_theme_block = str_starts_with( $style_path_norm, $theme_path_norm ); 238 239 if ( $is_theme_block ) { 240 $style_uri = get_theme_file_uri( str_replace( $theme_path_norm, '', $style_path_norm ) ); 241 } elseif ( $is_core_block ) { 242 $style_uri = includes_url( 'blocks/' . str_replace( 'core/', '', $metadata['name'] ) . "/style$suffix.css" ); 243 } 244 } else { 245 $style_uri = false; 246 } 247 248 $style_handle = generate_block_asset_handle( $metadata['name'], $field_name, $index ); 249 $version = ! $is_core_block && isset( $metadata['version'] ) ? $metadata['version'] : false; 250 $result = wp_register_style( 251 $style_handle, 252 $style_uri, 253 array(), 254 $version 255 ); 256 if ( ! $result ) { 257 return false; 258 } 259 260 if ( $has_style_file ) { 261 wp_style_add_data( $style_handle, 'path', $style_path_norm ); 262 263 if ( $is_core_block ) { 264 $rtl_file = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $style_path_norm ); 265 } else { 266 $rtl_file = str_replace( '.css', '-rtl.css', $style_path_norm ); 267 } 268 269 if ( is_rtl() && file_exists( $rtl_file ) ) { 270 wp_style_add_data( $style_handle, 'rtl', 'replace' ); 271 wp_style_add_data( $style_handle, 'suffix', $suffix ); 272 wp_style_add_data( $style_handle, 'path', $rtl_file ); 273 } 274 } 275 276 return $style_handle; 277 } 278 279 /** 280 * Gets i18n schema for block's metadata read from `block.json` file. 281 * 282 * @since 5.9.0 283 * 284 * @return object The schema for block's metadata. 285 */ 286 function get_block_metadata_i18n_schema() { 287 static $i18n_block_schema; 288 289 if ( ! isset( $i18n_block_schema ) ) { 290 $i18n_block_schema = wp_json_file_decode( __DIR__ . '/block-i18n.json' ); 291 } 292 293 return $i18n_block_schema; 294 } 295 296 /** 297 * Registers a block type from the metadata stored in the `block.json` file. 298 * 299 * @since 5.5.0 300 * @since 5.7.0 Added support for `textdomain` field and i18n handling for all translatable fields. 301 * @since 5.9.0 Added support for `variations` and `viewScript` fields. 302 * @since 6.1.0 Added support for `render` field. 303 * @since 6.3.0 Added `selectors` field. 304 * 305 * @param string $file_or_folder Path to the JSON file with metadata definition for 306 * the block or path to the folder where the `block.json` file is located. 307 * If providing the path to a JSON file, the filename must end with `block.json`. 308 * @param array $args Optional. Array of block type arguments. Accepts any public property 309 * of `WP_Block_Type`. See WP_Block_Type::__construct() for information 310 * on accepted arguments. Default empty array. 311 * @return WP_Block_Type|false The registered block type on success, or false on failure. 312 */ 313 function register_block_type_from_metadata( $file_or_folder, $args = array() ) { 314 /* 315 * Get an array of metadata from a PHP file. 316 * This improves performance for core blocks as it's only necessary to read a single PHP file 317 * instead of reading a JSON file per-block, and then decoding from JSON to PHP. 318 * Using a static variable ensures that the metadata is only read once per request. 319 */ 320 static $core_blocks_meta; 321 if ( ! $core_blocks_meta ) { 322 $core_blocks_meta = require_once ABSPATH . WPINC . '/blocks/blocks-json.php'; 323 } 324 325 $metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ? 326 trailingslashit( $file_or_folder ) . 'block.json' : 327 $file_or_folder; 328 329 if ( ! file_exists( $metadata_file ) ) { 330 return false; 331 } 332 333 // Try to get metadata from the static cache for core blocks. 334 $metadata = false; 335 if ( str_starts_with( $file_or_folder, ABSPATH . WPINC ) ) { 336 $core_block_name = str_replace( ABSPATH . WPINC . '/blocks/', '', $file_or_folder ); 337 if ( ! empty( $core_blocks_meta[ $core_block_name ] ) ) { 338 $metadata = $core_blocks_meta[ $core_block_name ]; 339 } 340 } 341 342 // If metadata is not found in the static cache, read it from the file. 343 if ( ! $metadata ) { 344 $metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) ); 345 } 346 347 if ( ! is_array( $metadata ) || empty( $metadata['name'] ) ) { 348 return false; 349 } 350 $metadata['file'] = wp_normalize_path( realpath( $metadata_file ) ); 351 352 /** 353 * Filters the metadata provided for registering a block type. 354 * 355 * @since 5.7.0 356 * 357 * @param array $metadata Metadata for registering a block type. 358 */ 359 $metadata = apply_filters( 'block_type_metadata', $metadata ); 360 361 // Add `style` and `editor_style` for core blocks if missing. 362 if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) { 363 $block_name = str_replace( 'core/', '', $metadata['name'] ); 364 365 if ( ! isset( $metadata['style'] ) ) { 366 $metadata['style'] = "wp-block-$block_name"; 367 } 368 if ( ! isset( $metadata['editorStyle'] ) ) { 369 $metadata['editorStyle'] = "wp-block-{$block_name}-editor"; 370 } 371 } 372 373 $settings = array(); 374 $property_mappings = array( 375 'apiVersion' => 'api_version', 376 'title' => 'title', 377 'category' => 'category', 378 'parent' => 'parent', 379 'ancestor' => 'ancestor', 380 'icon' => 'icon', 381 'description' => 'description', 382 'keywords' => 'keywords', 383 'attributes' => 'attributes', 384 'providesContext' => 'provides_context', 385 'usesContext' => 'uses_context', 386 'selectors' => 'selectors', 387 'supports' => 'supports', 388 'styles' => 'styles', 389 'variations' => 'variations', 390 'example' => 'example', 391 ); 392 $textdomain = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null; 393 $i18n_schema = get_block_metadata_i18n_schema(); 394 395 foreach ( $property_mappings as $key => $mapped_key ) { 396 if ( isset( $metadata[ $key ] ) ) { 397 $settings[ $mapped_key ] = $metadata[ $key ]; 398 if ( $textdomain && isset( $i18n_schema->$key ) ) { 399 $settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain ); 400 } 401 } 402 } 403 404 $script_fields = array( 405 'editorScript' => 'editor_script_handles', 406 'script' => 'script_handles', 407 'viewScript' => 'view_script_handles', 408 ); 409 foreach ( $script_fields as $metadata_field_name => $settings_field_name ) { 410 if ( ! empty( $metadata[ $metadata_field_name ] ) ) { 411 $scripts = $metadata[ $metadata_field_name ]; 412 $processed_scripts = array(); 413 if ( is_array( $scripts ) ) { 414 for ( $index = 0; $index < count( $scripts ); $index++ ) { 415 $result = register_block_script_handle( 416 $metadata, 417 $metadata_field_name, 418 $index 419 ); 420 if ( $result ) { 421 $processed_scripts[] = $result; 422 } 423 } 424 } else { 425 $result = register_block_script_handle( 426 $metadata, 427 $metadata_field_name 428 ); 429 if ( $result ) { 430 $processed_scripts[] = $result; 431 } 432 } 433 $settings[ $settings_field_name ] = $processed_scripts; 434 } 435 } 436 437 $style_fields = array( 438 'editorStyle' => 'editor_style_handles', 439 'style' => 'style_handles', 440 ); 441 foreach ( $style_fields as $metadata_field_name => $settings_field_name ) { 442 if ( ! empty( $metadata[ $metadata_field_name ] ) ) { 443 $styles = $metadata[ $metadata_field_name ]; 444 $processed_styles = array(); 445 if ( is_array( $styles ) ) { 446 for ( $index = 0; $index < count( $styles ); $index++ ) { 447 $result = register_block_style_handle( 448 $metadata, 449 $metadata_field_name, 450 $index 451 ); 452 if ( $result ) { 453 $processed_styles[] = $result; 454 } 455 } 456 } else { 457 $result = register_block_style_handle( 458 $metadata, 459 $metadata_field_name 460 ); 461 if ( $result ) { 462 $processed_styles[] = $result; 463 } 464 } 465 $settings[ $settings_field_name ] = $processed_styles; 466 } 467 } 468 469 if ( ! empty( $metadata['render'] ) ) { 470 $template_path = wp_normalize_path( 471 realpath( 472 dirname( $metadata['file'] ) . '/' . 473 remove_block_asset_path_prefix( $metadata['render'] ) 474 ) 475 ); 476 if ( $template_path ) { 477 /** 478 * Renders the block on the server. 479 * 480 * @since 6.1.0 481 * 482 * @param array $attributes Block attributes. 483 * @param string $content Block default content. 484 * @param WP_Block $block Block instance. 485 * 486 * @return string Returns the block content. 487 */ 488 $settings['render_callback'] = static function( $attributes, $content, $block ) use ( $template_path ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable 489 ob_start(); 490 require $template_path; 491 return ob_get_clean(); 492 }; 493 } 494 } 495 496 /** 497 * Filters the settings determined from the block type metadata. 498 * 499 * @since 5.7.0 500 * 501 * @param array $settings Array of determined settings for registering a block type. 502 * @param array $metadata Metadata provided for registering a block type. 503 */ 504 $settings = apply_filters( 505 'block_type_metadata_settings', 506 array_merge( 507 $settings, 508 $args 509 ), 510 $metadata 511 ); 512 513 return WP_Block_Type_Registry::get_instance()->register( 514 $metadata['name'], 515 $settings 516 ); 517 } 518 519 /** 520 * Registers a block type. The recommended way is to register a block type using 521 * the metadata stored in the `block.json` file. 522 * 523 * @since 5.0.0 524 * @since 5.8.0 First parameter now accepts a path to the `block.json` file. 525 * 526 * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively 527 * a path to the JSON file with metadata definition for the block, 528 * or a path to the folder where the `block.json` file is located, 529 * or a complete WP_Block_Type instance. 530 * In case a WP_Block_Type is provided, the $args parameter will be ignored. 531 * @param array $args Optional. Array of block type arguments. Accepts any public property 532 * of `WP_Block_Type`. See WP_Block_Type::__construct() for information 533 * on accepted arguments. Default empty array. 534 * 535 * @return WP_Block_Type|false The registered block type on success, or false on failure. 536 */ 537 function register_block_type( $block_type, $args = array() ) { 538 if ( is_string( $block_type ) && file_exists( $block_type ) ) { 539 return register_block_type_from_metadata( $block_type, $args ); 540 } 541 542 return WP_Block_Type_Registry::get_instance()->register( $block_type, $args ); 543 } 544 545 /** 546 * Unregisters a block type. 547 * 548 * @since 5.0.0 549 * 550 * @param string|WP_Block_Type $name Block type name including namespace, or alternatively 551 * a complete WP_Block_Type instance. 552 * @return WP_Block_Type|false The unregistered block type on success, or false on failure. 553 */ 554 function unregister_block_type( $name ) { 555 return WP_Block_Type_Registry::get_instance()->unregister( $name ); 556 } 557 558 /** 559 * Determines whether a post or content string has blocks. 560 * 561 * This test optimizes for performance rather than strict accuracy, detecting 562 * the pattern of a block but not validating its structure. For strict accuracy, 563 * you should use the block parser on post content. 564 * 565 * @since 5.0.0 566 * 567 * @see parse_blocks() 568 * 569 * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. 570 * Defaults to global $post. 571 * @return bool Whether the post has blocks. 572 */ 573 function has_blocks( $post = null ) { 574 if ( ! is_string( $post ) ) { 575 $wp_post = get_post( $post ); 576 577 if ( ! $wp_post instanceof WP_Post ) { 578 return false; 579 } 580 581 $post = $wp_post->post_content; 582 } 583 584 return false !== strpos( (string) $post, '<!-- wp:' ); 585 } 586 587 /** 588 * Determines whether a $post or a string contains a specific block type. 589 * 590 * This test optimizes for performance rather than strict accuracy, detecting 591 * whether the block type exists but not validating its structure and not checking 592 * reusable blocks. For strict accuracy, you should use the block parser on post content. 593 * 594 * @since 5.0.0 595 * 596 * @see parse_blocks() 597 * 598 * @param string $block_name Full block type to look for. 599 * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. 600 * Defaults to global $post. 601 * @return bool Whether the post content contains the specified block. 602 */ 603 function has_block( $block_name, $post = null ) { 604 if ( ! has_blocks( $post ) ) { 605 return false; 606 } 607 608 if ( ! is_string( $post ) ) { 609 $wp_post = get_post( $post ); 610 if ( $wp_post instanceof WP_Post ) { 611 $post = $wp_post->post_content; 612 } 613 } 614 615 /* 616 * Normalize block name to include namespace, if provided as non-namespaced. 617 * This matches behavior for WordPress 5.0.0 - 5.3.0 in matching blocks by 618 * their serialized names. 619 */ 620 if ( false === strpos( $block_name, '/' ) ) { 621 $block_name = 'core/' . $block_name; 622 } 623 624 // Test for existence of block by its fully qualified name. 625 $has_block = false !== strpos( $post, '<!-- wp:' . $block_name . ' ' ); 626 627 if ( ! $has_block ) { 628 /* 629 * If the given block name would serialize to a different name, test for 630 * existence by the serialized form. 631 */ 632 $serialized_block_name = strip_core_block_namespace( $block_name ); 633 if ( $serialized_block_name !== $block_name ) { 634 $has_block = false !== strpos( $post, '<!-- wp:' . $serialized_block_name . ' ' ); 635 } 636 } 637 638 return $has_block; 639 } 640 641 /** 642 * Returns an array of the names of all registered dynamic block types. 643 * 644 * @since 5.0.0 645 * 646 * @return string[] Array of dynamic block names. 647 */ 648 function get_dynamic_block_names() { 649 $dynamic_block_names = array(); 650 651 $block_types = WP_Block_Type_Registry::get_instance()->get_all_registered(); 652 foreach ( $block_types as $block_type ) { 653 if ( $block_type->is_dynamic() ) { 654 $dynamic_block_names[] = $block_type->name; 655 } 656 } 657 658 return $dynamic_block_names; 659 } 660 661 /** 662 * Given an array of attributes, returns a string in the serialized attributes 663 * format prepared for post content. 664 * 665 * The serialized result is a JSON-encoded string, with unicode escape sequence 666 * substitution for characters which might otherwise interfere with embedding 667 * the result in an HTML comment. 668 * 669 * This function must produce output that remains in sync with the output of 670 * the serializeAttributes JavaScript function in the block editor in order 671 * to ensure consistent operation between PHP and JavaScript. 672 * 673 * @since 5.3.1 674 * 675 * @param array $block_attributes Attributes object. 676 * @return string Serialized attributes. 677 */ 678 function serialize_block_attributes( $block_attributes ) { 679 $encoded_attributes = wp_json_encode( $block_attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); 680 $encoded_attributes = preg_replace( '/--/', '\\u002d\\u002d', $encoded_attributes ); 681 $encoded_attributes = preg_replace( '/</', '\\u003c', $encoded_attributes ); 682 $encoded_attributes = preg_replace( '/>/', '\\u003e', $encoded_attributes ); 683 $encoded_attributes = preg_replace( '/&/', '\\u0026', $encoded_attributes ); 684 // Regex: /\\"/ 685 $encoded_attributes = preg_replace( '/\\\\"/', '\\u0022', $encoded_attributes ); 686 687 return $encoded_attributes; 688 } 689 690 /** 691 * Returns the block name to use for serialization. This will remove the default 692 * "core/" namespace from a block name. 693 * 694 * @since 5.3.1 695 * 696 * @param string|null $block_name Optional. Original block name. Null if the block name is unknown, 697 * e.g. Classic blocks have their name set to null. Default null. 698 * @return string Block name to use for serialization. 699 */ 700 function strip_core_block_namespace( $block_name = null ) { 701 if ( is_string( $block_name ) && str_starts_with( $block_name, 'core/' ) ) { 702 return substr( $block_name, 5 ); 703 } 704 705 return $block_name; 706 } 707 708 /** 709 * Returns the content of a block, including comment delimiters. 710 * 711 * @since 5.3.1 712 * 713 * @param string|null $block_name Block name. Null if the block name is unknown, 714 * e.g. Classic blocks have their name set to null. 715 * @param array $block_attributes Block attributes. 716 * @param string $block_content Block save content. 717 * @return string Comment-delimited block content. 718 */ 719 function get_comment_delimited_block_content( $block_name, $block_attributes, $block_content ) { 720 if ( is_null( $block_name ) ) { 721 return $block_content; 722 } 723 724 $serialized_block_name = strip_core_block_namespace( $block_name ); 725 $serialized_attributes = empty( $block_attributes ) ? '' : serialize_block_attributes( $block_attributes ) . ' '; 726 727 if ( empty( $block_content ) ) { 728 return sprintf( '<!-- wp:%s %s/-->', $serialized_block_name, $serialized_attributes ); 729 } 730 731 return sprintf( 732 '<!-- wp:%s %s-->%s<!-- /wp:%s -->', 733 $serialized_block_name, 734 $serialized_attributes, 735 $block_content, 736 $serialized_block_name 737 ); 738 } 739 740 /** 741 * Returns the content of a block, including comment delimiters, serializing all 742 * attributes from the given parsed block. 743 * 744 * This should be used when preparing a block to be saved to post content. 745 * Prefer `render_block` when preparing a block for display. Unlike 746 * `render_block`, this does not evaluate a block's `render_callback`, and will 747 * instead preserve the markup as parsed. 748 * 749 * @since 5.3.1 750 * 751 * @param array $block A representative array of a single parsed block object. See WP_Block_Parser_Block. 752 * @return string String of rendered HTML. 753 */ 754 function serialize_block( $block ) { 755 $block_content = ''; 756 757 $index = 0; 758 foreach ( $block['innerContent'] as $chunk ) { 759 $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] ); 760 } 761 762 if ( ! is_array( $block['attrs'] ) ) { 763 $block['attrs'] = array(); 764 } 765 766 return get_comment_delimited_block_content( 767 $block['blockName'], 768 $block['attrs'], 769 $block_content 770 ); 771 } 772 773 /** 774 * Returns a joined string of the aggregate serialization of the given 775 * parsed blocks. 776 * 777 * @since 5.3.1 778 * 779 * @param array[] $blocks An array of representative arrays of parsed block objects. See serialize_block(). 780 * @return string String of rendered HTML. 781 */ 782 function serialize_blocks( $blocks ) { 783 return implode( '', array_map( 'serialize_block', $blocks ) ); 784 } 785 786 /** 787 * Filters and sanitizes block content to remove non-allowable HTML 788 * from parsed block attribute values. 789 * 790 * @since 5.3.1 791 * 792 * @param string $text Text that may contain block content. 793 * @param array[]|string $allowed_html Optional. An array of allowed HTML elements and attributes, 794 * or a context name such as 'post'. See wp_kses_allowed_html() 795 * for the list of accepted context names. Default 'post'. 796 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 797 * Defaults to the result of wp_allowed_protocols(). 798 * @return string The filtered and sanitized content result. 799 */ 800 function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) { 801 $result = ''; 802 803 if ( false !== strpos( $text, '<!--' ) && false !== strpos( $text, '--->' ) ) { 804 $text = preg_replace_callback( '%<!--(.*?)--->%', '_filter_block_content_callback', $text ); 805 } 806 807 $blocks = parse_blocks( $text ); 808 foreach ( $blocks as $block ) { 809 $block = filter_block_kses( $block, $allowed_html, $allowed_protocols ); 810 $result .= serialize_block( $block ); 811 } 812 813 return $result; 814 } 815 816 /** 817 * Callback used for regular expression replacement in filter_block_content(). 818 * 819 * @private 820 * @since 6.2.1 821 * 822 * @param array $matches Array of preg_replace_callback matches. 823 * @return string Replacement string. 824 */ 825 function _filter_block_content_callback( $matches ) { 826 return '<!--' . rtrim( $matches[1], '-' ) . '-->'; 827 } 828 829 /** 830 * Filters and sanitizes a parsed block to remove non-allowable HTML 831 * from block attribute values. 832 * 833 * @since 5.3.1 834 * 835 * @param WP_Block_Parser_Block $block The parsed block object. 836 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 837 * or a context name such as 'post'. See wp_kses_allowed_html() 838 * for the list of accepted context names. 839 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 840 * Defaults to the result of wp_allowed_protocols(). 841 * @return array The filtered and sanitized block object result. 842 */ 843 function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) { 844 $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols ); 845 846 if ( is_array( $block['innerBlocks'] ) ) { 847 foreach ( $block['innerBlocks'] as $i => $inner_block ) { 848 $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols ); 849 } 850 } 851 852 return $block; 853 } 854 855 /** 856 * Filters and sanitizes a parsed block attribute value to remove 857 * non-allowable HTML. 858 * 859 * @since 5.3.1 860 * 861 * @param string[]|string $value The attribute value to filter. 862 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 863 * or a context name such as 'post'. See wp_kses_allowed_html() 864 * for the list of accepted context names. 865 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 866 * Defaults to the result of wp_allowed_protocols(). 867 * @return string[]|string The filtered and sanitized result. 868 */ 869 function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array() ) { 870 if ( is_array( $value ) ) { 871 foreach ( $value as $key => $inner_value ) { 872 $filtered_key = filter_block_kses_value( $key, $allowed_html, $allowed_protocols ); 873 $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols ); 874 875 if ( $filtered_key !== $key ) { 876 unset( $value[ $key ] ); 877 } 878 879 $value[ $filtered_key ] = $filtered_value; 880 } 881 } elseif ( is_string( $value ) ) { 882 return wp_kses( $value, $allowed_html, $allowed_protocols ); 883 } 884 885 return $value; 886 } 887 888 /** 889 * Parses blocks out of a content string, and renders those appropriate for the excerpt. 890 * 891 * As the excerpt should be a small string of text relevant to the full post content, 892 * this function renders the blocks that are most likely to contain such text. 893 * 894 * @since 5.0.0 895 * 896 * @param string $content The content to parse. 897 * @return string The parsed and filtered content. 898 */ 899 function excerpt_remove_blocks( $content ) { 900 $allowed_inner_blocks = array( 901 // Classic blocks have their blockName set to null. 902 null, 903 'core/freeform', 904 'core/heading', 905 'core/html', 906 'core/list', 907 'core/media-text', 908 'core/paragraph', 909 'core/preformatted', 910 'core/pullquote', 911 'core/quote', 912 'core/table', 913 'core/verse', 914 ); 915 916 $allowed_wrapper_blocks = array( 917 'core/columns', 918 'core/column', 919 'core/group', 920 ); 921 922 /** 923 * Filters the list of blocks that can be used as wrapper blocks, allowing 924 * excerpts to be generated from the `innerBlocks` of these wrappers. 925 * 926 * @since 5.8.0 927 * 928 * @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks. 929 */ 930 $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks ); 931 932 $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks ); 933 934 /** 935 * Filters the list of blocks that can contribute to the excerpt. 936 * 937 * If a dynamic block is added to this list, it must not generate another 938 * excerpt, as this will cause an infinite loop to occur. 939 * 940 * @since 5.0.0 941 * 942 * @param string[] $allowed_blocks The list of names of allowed blocks. 943 */ 944 $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks ); 945 $blocks = parse_blocks( $content ); 946 $output = ''; 947 948 foreach ( $blocks as $block ) { 949 if ( in_array( $block['blockName'], $allowed_blocks, true ) ) { 950 if ( ! empty( $block['innerBlocks'] ) ) { 951 if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) { 952 $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks ); 953 continue; 954 } 955 956 // Skip the block if it has disallowed or nested inner blocks. 957 foreach ( $block['innerBlocks'] as $inner_block ) { 958 if ( 959 ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) || 960 ! empty( $inner_block['innerBlocks'] ) 961 ) { 962 continue 2; 963 } 964 } 965 } 966 967 $output .= render_block( $block ); 968 } 969 } 970 971 return $output; 972 } 973 974 /** 975 * Renders inner blocks from the allowed wrapper blocks 976 * for generating an excerpt. 977 * 978 * @since 5.8.0 979 * @access private 980 * 981 * @param array $parsed_block The parsed block. 982 * @param array $allowed_blocks The list of allowed inner blocks. 983 * @return string The rendered inner blocks. 984 */ 985 function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) { 986 $output = ''; 987 988 foreach ( $parsed_block['innerBlocks'] as $inner_block ) { 989 if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) { 990 continue; 991 } 992 993 if ( empty( $inner_block['innerBlocks'] ) ) { 994 $output .= render_block( $inner_block ); 995 } else { 996 $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks ); 997 } 998 } 999 1000 return $output; 1001 } 1002 1003 /** 1004 * Renders a single block into a HTML string. 1005 * 1006 * @since 5.0.0 1007 * 1008 * @global WP_Post $post The post to edit. 1009 * 1010 * @param array $parsed_block A single parsed block object. 1011 * @return string String of rendered HTML. 1012 */ 1013 function render_block( $parsed_block ) { 1014 global $post; 1015 $parent_block = null; 1016 1017 /** 1018 * Allows render_block() to be short-circuited, by returning a non-null value. 1019 * 1020 * @since 5.1.0 1021 * @since 5.9.0 The `$parent_block` parameter was added. 1022 * 1023 * @param string|null $pre_render The pre-rendered content. Default null. 1024 * @param array $parsed_block The block being rendered. 1025 * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. 1026 */ 1027 $pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block ); 1028 if ( ! is_null( $pre_render ) ) { 1029 return $pre_render; 1030 } 1031 1032 $source_block = $parsed_block; 1033 1034 /** 1035 * Filters the block being rendered in render_block(), before it's processed. 1036 * 1037 * @since 5.1.0 1038 * @since 5.9.0 The `$parent_block` parameter was added. 1039 * 1040 * @param array $parsed_block The block being rendered. 1041 * @param array $source_block An un-modified copy of $parsed_block, as it appeared in the source content. 1042 * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. 1043 */ 1044 $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block ); 1045 1046 $context = array(); 1047 1048 if ( $post instanceof WP_Post ) { 1049 $context['postId'] = $post->ID; 1050 1051 /* 1052 * The `postType` context is largely unnecessary server-side, since the ID 1053 * is usually sufficient on its own. That being said, since a block's 1054 * manifest is expected to be shared between the server and the client, 1055 * it should be included to consistently fulfill the expectation. 1056 */ 1057 $context['postType'] = $post->post_type; 1058 } 1059 1060 /** 1061 * Filters the default context provided to a rendered block. 1062 * 1063 * @since 5.5.0 1064 * @since 5.9.0 The `$parent_block` parameter was added. 1065 * 1066 * @param array $context Default context. 1067 * @param array $parsed_block Block being rendered, filtered by `render_block_data`. 1068 * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. 1069 */ 1070 $context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block ); 1071 1072 $block = new WP_Block( $parsed_block, $context ); 1073 1074 return $block->render(); 1075 } 1076 1077 /** 1078 * Parses blocks out of a content string. 1079 * 1080 * @since 5.0.0 1081 * 1082 * @param string $content Post content. 1083 * @return array[] Array of parsed block objects. 1084 */ 1085 function parse_blocks( $content ) { 1086 /** 1087 * Filter to allow plugins to replace the server-side block parser. 1088 * 1089 * @since 5.0.0 1090 * 1091 * @param string $parser_class Name of block parser class. 1092 */ 1093 $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' ); 1094 1095 $parser = new $parser_class(); 1096 return $parser->parse( $content ); 1097 } 1098 1099 /** 1100 * Parses dynamic blocks out of `post_content` and re-renders them. 1101 * 1102 * @since 5.0.0 1103 * 1104 * @param string $content Post content. 1105 * @return string Updated post content. 1106 */ 1107 function do_blocks( $content ) { 1108 $blocks = parse_blocks( $content ); 1109 $output = ''; 1110 1111 foreach ( $blocks as $block ) { 1112 $output .= render_block( $block ); 1113 } 1114 1115 // If there are blocks in this content, we shouldn't run wpautop() on it later. 1116 $priority = has_filter( 'the_content', 'wpautop' ); 1117 if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) { 1118 remove_filter( 'the_content', 'wpautop', $priority ); 1119 add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 ); 1120 } 1121 1122 return $output; 1123 } 1124 1125 /** 1126 * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards, 1127 * for subsequent `the_content` usage. 1128 * 1129 * @since 5.0.0 1130 * @access private 1131 * 1132 * @param string $content The post content running through this filter. 1133 * @return string The unmodified content. 1134 */ 1135 function _restore_wpautop_hook( $content ) { 1136 $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' ); 1137 1138 add_filter( 'the_content', 'wpautop', $current_priority - 1 ); 1139 remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority ); 1140 1141 return $content; 1142 } 1143 1144 /** 1145 * Returns the current version of the block format that the content string is using. 1146 * 1147 * If the string doesn't contain blocks, it returns 0. 1148 * 1149 * @since 5.0.0 1150 * 1151 * @param string $content Content to test. 1152 * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise. 1153 */ 1154 function block_version( $content ) { 1155 return has_blocks( $content ) ? 1 : 0; 1156 } 1157 1158 /** 1159 * Registers a new block style. 1160 * 1161 * @since 5.3.0 1162 * 1163 * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/ 1164 * 1165 * @param string $block_name Block type name including namespace. 1166 * @param array $style_properties Array containing the properties of the style name, 1167 * label, style (name of the stylesheet to be enqueued), 1168 * inline_style (string containing the CSS to be added). 1169 * @return bool True if the block style was registered with success and false otherwise. 1170 */ 1171 function register_block_style( $block_name, $style_properties ) { 1172 return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties ); 1173 } 1174 1175 /** 1176 * Unregisters a block style. 1177 * 1178 * @since 5.3.0 1179 * 1180 * @param string $block_name Block type name including namespace. 1181 * @param string $block_style_name Block style name. 1182 * @return bool True if the block style was unregistered with success and false otherwise. 1183 */ 1184 function unregister_block_style( $block_name, $block_style_name ) { 1185 return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name ); 1186 } 1187 1188 /** 1189 * Checks whether the current block type supports the feature requested. 1190 * 1191 * @since 5.8.0 1192 * 1193 * @param WP_Block_Type $block_type Block type to check for support. 1194 * @param array $feature Path to a specific feature to check support for. 1195 * @param mixed $default_value Optional. Fallback value for feature support. Default false. 1196 * @return bool Whether the feature is supported. 1197 */ 1198 function block_has_support( $block_type, $feature, $default_value = false ) { 1199 $block_support = $default_value; 1200 if ( $block_type && property_exists( $block_type, 'supports' ) ) { 1201 $block_support = _wp_array_get( $block_type->supports, $feature, $default_value ); 1202 } 1203 1204 return true === $block_support || is_array( $block_support ); 1205 } 1206 1207 /** 1208 * Converts typography keys declared under `supports.*` to `supports.typography.*`. 1209 * 1210 * Displays a `_doing_it_wrong()` notice when a block using the older format is detected. 1211 * 1212 * @since 5.8.0 1213 * 1214 * @param array $metadata Metadata for registering a block type. 1215 * @return array Filtered metadata for registering a block type. 1216 */ 1217 function wp_migrate_old_typography_shape( $metadata ) { 1218 if ( ! isset( $metadata['supports'] ) ) { 1219 return $metadata; 1220 } 1221 1222 $typography_keys = array( 1223 '__experimentalFontFamily', 1224 '__experimentalFontStyle', 1225 '__experimentalFontWeight', 1226 '__experimentalLetterSpacing', 1227 '__experimentalTextDecoration', 1228 '__experimentalTextTransform', 1229 'fontSize', 1230 'lineHeight', 1231 ); 1232 1233 foreach ( $typography_keys as $typography_key ) { 1234 $support_for_key = _wp_array_get( $metadata['supports'], array( $typography_key ), null ); 1235 1236 if ( null !== $support_for_key ) { 1237 _doing_it_wrong( 1238 'register_block_type_from_metadata()', 1239 sprintf( 1240 /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */ 1241 __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ), 1242 $metadata['name'], 1243 "<code>$typography_key</code>", 1244 '<code>block.json</code>', 1245 "<code>supports.$typography_key</code>", 1246 "<code>supports.typography.$typography_key</code>" 1247 ), 1248 '5.8.0' 1249 ); 1250 1251 _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key ); 1252 unset( $metadata['supports'][ $typography_key ] ); 1253 } 1254 } 1255 1256 return $metadata; 1257 } 1258 1259 /** 1260 * Helper function that constructs a WP_Query args array from 1261 * a `Query` block properties. 1262 * 1263 * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks. 1264 * 1265 * @since 5.8.0 1266 * @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query. 1267 * 1268 * @param WP_Block $block Block instance. 1269 * @param int $page Current query's page. 1270 * 1271 * @return array Returns the constructed WP_Query arguments. 1272 */ 1273 function build_query_vars_from_query_block( $block, $page ) { 1274 $query = array( 1275 'post_type' => 'post', 1276 'order' => 'DESC', 1277 'orderby' => 'date', 1278 'post__not_in' => array(), 1279 ); 1280 1281 if ( isset( $block->context['query'] ) ) { 1282 if ( ! empty( $block->context['query']['postType'] ) ) { 1283 $post_type_param = $block->context['query']['postType']; 1284 if ( is_post_type_viewable( $post_type_param ) ) { 1285 $query['post_type'] = $post_type_param; 1286 } 1287 } 1288 if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) { 1289 $sticky = get_option( 'sticky_posts' ); 1290 if ( 'only' === $block->context['query']['sticky'] ) { 1291 /* 1292 * Passing an empty array to post__in will return have_posts() as true (and all posts will be returned). 1293 * Logic should be used before hand to determine if WP_Query should be used in the event that the array 1294 * being passed to post__in is empty. 1295 * 1296 * @see https://core.trac.wordpress.org/ticket/28099 1297 */ 1298 $query['post__in'] = ! empty( $sticky ) ? $sticky : array( 0 ); 1299 $query['ignore_sticky_posts'] = 1; 1300 } else { 1301 $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky ); 1302 } 1303 } 1304 if ( ! empty( $block->context['query']['exclude'] ) ) { 1305 $excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] ); 1306 $excluded_post_ids = array_filter( $excluded_post_ids ); 1307 $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids ); 1308 } 1309 if ( 1310 isset( $block->context['query']['perPage'] ) && 1311 is_numeric( $block->context['query']['perPage'] ) 1312 ) { 1313 $per_page = absint( $block->context['query']['perPage'] ); 1314 $offset = 0; 1315 1316 if ( 1317 isset( $block->context['query']['offset'] ) && 1318 is_numeric( $block->context['query']['offset'] ) 1319 ) { 1320 $offset = absint( $block->context['query']['offset'] ); 1321 } 1322 1323 $query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset; 1324 $query['posts_per_page'] = $per_page; 1325 } 1326 // Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility. 1327 if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) { 1328 $tax_query = array(); 1329 if ( ! empty( $block->context['query']['categoryIds'] ) ) { 1330 $tax_query[] = array( 1331 'taxonomy' => 'category', 1332 'terms' => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ), 1333 'include_children' => false, 1334 ); 1335 } 1336 if ( ! empty( $block->context['query']['tagIds'] ) ) { 1337 $tax_query[] = array( 1338 'taxonomy' => 'post_tag', 1339 'terms' => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ), 1340 'include_children' => false, 1341 ); 1342 } 1343 $query['tax_query'] = $tax_query; 1344 } 1345 if ( ! empty( $block->context['query']['taxQuery'] ) ) { 1346 $query['tax_query'] = array(); 1347 foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) { 1348 if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) { 1349 $query['tax_query'][] = array( 1350 'taxonomy' => $taxonomy, 1351 'terms' => array_filter( array_map( 'intval', $terms ) ), 1352 'include_children' => false, 1353 ); 1354 } 1355 } 1356 } 1357 if ( 1358 isset( $block->context['query']['order'] ) && 1359 in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true ) 1360 ) { 1361 $query['order'] = strtoupper( $block->context['query']['order'] ); 1362 } 1363 if ( isset( $block->context['query']['orderBy'] ) ) { 1364 $query['orderby'] = $block->context['query']['orderBy']; 1365 } 1366 if ( 1367 isset( $block->context['query']['author'] ) && 1368 (int) $block->context['query']['author'] > 0 1369 ) { 1370 $query['author'] = (int) $block->context['query']['author']; 1371 } 1372 if ( ! empty( $block->context['query']['search'] ) ) { 1373 $query['s'] = $block->context['query']['search']; 1374 } 1375 if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) { 1376 $query['post_parent__in'] = array_filter( array_map( 'intval', $block->context['query']['parents'] ) ); 1377 } 1378 } 1379 1380 /** 1381 * Filters the arguments which will be passed to `WP_Query` for the Query Loop Block. 1382 * 1383 * Anything to this filter should be compatible with the `WP_Query` API to form 1384 * the query context which will be passed down to the Query Loop Block's children. 1385 * This can help, for example, to include additional settings or meta queries not 1386 * directly supported by the core Query Loop Block, and extend its capabilities. 1387 * 1388 * Please note that this will only influence the query that will be rendered on the 1389 * front-end. The editor preview is not affected by this filter. Also, worth noting 1390 * that the editor preview uses the REST API, so, ideally, one should aim to provide 1391 * attributes which are also compatible with the REST API, in order to be able to 1392 * implement identical queries on both sides. 1393 * 1394 * @since 6.1.0 1395 * 1396 * @param array $query Array containing parameters for `WP_Query` as parsed by the block context. 1397 * @param WP_Block $block Block instance. 1398 * @param int $page Current query's page. 1399 */ 1400 return apply_filters( 'query_loop_block_query_vars', $query, $block, $page ); 1401 } 1402 1403 /** 1404 * Helper function that returns the proper pagination arrow HTML for 1405 * `QueryPaginationNext` and `QueryPaginationPrevious` blocks based 1406 * on the provided `paginationArrow` from `QueryPagination` context. 1407 * 1408 * It's used in QueryPaginationNext and QueryPaginationPrevious blocks. 1409 * 1410 * @since 5.9.0 1411 * 1412 * @param WP_Block $block Block instance. 1413 * @param bool $is_next Flag for handling `next/previous` blocks. 1414 * @return string|null The pagination arrow HTML or null if there is none. 1415 */ 1416 function get_query_pagination_arrow( $block, $is_next ) { 1417 $arrow_map = array( 1418 'none' => '', 1419 'arrow' => array( 1420 'next' => '→', 1421 'previous' => '←', 1422 ), 1423 'chevron' => array( 1424 'next' => '»', 1425 'previous' => '«', 1426 ), 1427 ); 1428 if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) { 1429 $pagination_type = $is_next ? 'next' : 'previous'; 1430 $arrow_attribute = $block->context['paginationArrow']; 1431 $arrow = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ]; 1432 $arrow_classes = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute"; 1433 return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>"; 1434 } 1435 return null; 1436 } 1437 1438 /** 1439 * Helper function that constructs a comment query vars array from the passed 1440 * block properties. 1441 * 1442 * It's used with the Comment Query Loop inner blocks. 1443 * 1444 * @since 6.0.0 1445 * 1446 * @param WP_Block $block Block instance. 1447 * @return array Returns the comment query parameters to use with the 1448 * WP_Comment_Query constructor. 1449 */ 1450 function build_comment_query_vars_from_block( $block ) { 1451 1452 $comment_args = array( 1453 'orderby' => 'comment_date_gmt', 1454 'order' => 'ASC', 1455 'status' => 'approve', 1456 'no_found_rows' => false, 1457 ); 1458 1459 if ( is_user_logged_in() ) { 1460 $comment_args['include_unapproved'] = array( get_current_user_id() ); 1461 } else { 1462 $unapproved_email = wp_get_unapproved_comment_author_email(); 1463 1464 if ( $unapproved_email ) { 1465 $comment_args['include_unapproved'] = array( $unapproved_email ); 1466 } 1467 } 1468 1469 if ( ! empty( $block->context['postId'] ) ) { 1470 $comment_args['post_id'] = (int) $block->context['postId']; 1471 } 1472 1473 if ( get_option( 'thread_comments' ) ) { 1474 $comment_args['hierarchical'] = 'threaded'; 1475 } else { 1476 $comment_args['hierarchical'] = false; 1477 } 1478 1479 if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) { 1480 $per_page = get_option( 'comments_per_page' ); 1481 $default_page = get_option( 'default_comments_page' ); 1482 if ( $per_page > 0 ) { 1483 $comment_args['number'] = $per_page; 1484 1485 $page = (int) get_query_var( 'cpage' ); 1486 if ( $page ) { 1487 $comment_args['paged'] = $page; 1488 } elseif ( 'oldest' === $default_page ) { 1489 $comment_args['paged'] = 1; 1490 } elseif ( 'newest' === $default_page ) { 1491 $max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages; 1492 if ( 0 !== $max_num_pages ) { 1493 $comment_args['paged'] = $max_num_pages; 1494 } 1495 } 1496 // Set the `cpage` query var to ensure the previous and next pagination links are correct 1497 // when inheriting the Discussion Settings. 1498 if ( 0 === $page && isset( $comment_args['paged'] ) && $comment_args['paged'] > 0 ) { 1499 set_query_var( 'cpage', $comment_args['paged'] ); 1500 } 1501 } 1502 } 1503 1504 return $comment_args; 1505 } 1506 1507 /** 1508 * Helper function that returns the proper pagination arrow HTML for 1509 * `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the 1510 * provided `paginationArrow` from `CommentsPagination` context. 1511 * 1512 * It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks. 1513 * 1514 * @since 6.0.0 1515 * 1516 * @param WP_Block $block Block instance. 1517 * @param string $pagination_type Optional. Type of the arrow we will be rendering. 1518 * Accepts 'next' or 'previous'. Default 'next'. 1519 * @return string|null The pagination arrow HTML or null if there is none. 1520 */ 1521 function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) { 1522 $arrow_map = array( 1523 'none' => '', 1524 'arrow' => array( 1525 'next' => '→', 1526 'previous' => '←', 1527 ), 1528 'chevron' => array( 1529 'next' => '»', 1530 'previous' => '«', 1531 ), 1532 ); 1533 if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) { 1534 $arrow_attribute = $block->context['comments/paginationArrow']; 1535 $arrow = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ]; 1536 $arrow_classes = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute"; 1537 return "<span class='$arrow_classes' aria-hidden='true'>$arrow</span>"; 1538 } 1539 return null; 1540 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Sun Jun 4 08:20:02 2023 | Cross-referenced by PHPXref |