| 1 |
<?php |
| 2 |
/** |
| 3 |
* Hook callbacks used for Speculative Loading. |
| 4 |
* |
| 5 |
* @package speculation-rules |
| 6 |
* @since 1.0.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
// Exit if accessed directly. |
| 10 |
if ( ! defined( 'ABSPATH' ) ) { |
| 11 |
exit; |
| 12 |
} |
| 13 |
|
| 14 |
/** |
| 15 |
* Prints the speculation rules. |
| 16 |
* |
| 17 |
* For browsers that do not support speculation rules yet, the `script[type="speculationrules"]` tag will be ignored. |
| 18 |
* |
| 19 |
* @since 1.0.0 |
| 20 |
*/ |
| 21 |
function plsr_print_speculation_rules() { |
| 22 |
$rules = plsr_get_speculation_rules(); |
| 23 |
if ( empty( $rules ) ) { |
| 24 |
return; |
| 25 |
} |
| 26 |
|
| 27 |
// This workaround is needed for WP 6.4. See <https://core.trac.wordpress.org/ticket/60320>. |
| 28 |
$needs_html5_workaround = ( |
| 29 |
! current_theme_supports( 'html5', 'script' ) && |
| 30 |
version_compare( strtok( get_bloginfo( 'version' ), '-' ), '6.4', '>=' ) && |
| 31 |
version_compare( strtok( get_bloginfo( 'version' ), '-' ), '6.5', '<' ) |
| 32 |
); |
| 33 |
if ( $needs_html5_workaround ) { |
| 34 |
$backup_wp_theme_features = $GLOBALS['_wp_theme_features']; |
| 35 |
add_theme_support( 'html5', array( 'script' ) ); |
| 36 |
} |
| 37 |
|
| 38 |
wp_print_inline_script_tag( |
| 39 |
wp_json_encode( $rules ), |
| 40 |
array( 'type' => 'speculationrules' ) |
| 41 |
); |
| 42 |
|
| 43 |
if ( $needs_html5_workaround ) { |
| 44 |
$GLOBALS['_wp_theme_features'] = $backup_wp_theme_features; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited |
| 45 |
} |
| 46 |
} |
| 47 |
add_action( 'wp_footer', 'plsr_print_speculation_rules' ); |
| 48 |
|
| 49 |
/** |
| 50 |
* Displays the HTML generator meta tag for the Speculative Loading plugin. |
| 51 |
* |
| 52 |
* See {@see 'wp_head'}. |
| 53 |
* |
| 54 |
* @since 1.1.0 |
| 55 |
*/ |
| 56 |
function plsr_render_generator_meta_tag() { |
| 57 |
// Use the plugin slug as it is immutable. |
| 58 |
echo '<meta name="generator" content="speculation-rules ' . esc_attr( SPECULATION_RULES_VERSION ) . '">' . "\n"; |
| 59 |
} |
| 60 |
add_action( 'wp_head', 'plsr_render_generator_meta_tag' ); |
| 61 |
|