Make WordPress Core


Ignore:
Timestamp:
03/15/2024 12:10:49 PM (14 months ago)
Author:
swissspidy
Message:

Interactivity API: Do not print state if it’s an empty array.

This prunes stores and configurations that are empty arrays, as stores are expected to be JSON objects.
By not printing empty configurations, less redundant data is serialized into the HTML.

Props jonsurrell, luisherranz, darerodz, gziolo, swissspidy.
Fixes #60761.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/interactivity-api/class-wp-interactivity-api.php

    r57835 r57841  
    141141     */
    142142    public function print_client_interactivity_data() {
    143         $store      = array();
    144         $has_state  = ! empty( $this->state_data );
    145         $has_config = ! empty( $this->config_data );
    146 
    147         if ( $has_state || $has_config ) {
    148             if ( $has_config ) {
    149                 $store['config'] = $this->config_data;
    150             }
    151             if ( $has_state ) {
    152                 $store['state'] = $this->state_data;
    153             }
     143        if ( empty( $this->state_data ) && empty( $this->config_data ) ) {
     144            return;
     145        }
     146
     147        $interactivity_data = array();
     148
     149        $config = array();
     150        foreach ( $this->config_data as $key => $value ) {
     151            if ( ! empty( $value ) ) {
     152                $config[ $key ] = $value;
     153            }
     154        }
     155        if ( ! empty( $config ) ) {
     156            $interactivity_data['config'] = $config;
     157        }
     158
     159        $state = array();
     160        foreach ( $this->state_data as $key => $value ) {
     161            if ( ! empty( $value ) ) {
     162                $state[ $key ] = $value;
     163            }
     164        }
     165        if ( ! empty( $state ) ) {
     166            $interactivity_data['state'] = $state;
     167        }
     168
     169        if ( ! empty( $interactivity_data ) ) {
    154170            wp_print_inline_script_tag(
    155171                wp_json_encode(
    156                     $store,
     172                    $interactivity_data,
    157173                    JSON_HEX_TAG | JSON_HEX_AMP
    158174                ),
Note: See TracChangeset for help on using the changeset viewer.