[wp-trac] [WordPress Trac] #62136: Interactivity API: Allow reading element attributes inside derived state props

WordPress Trac noreply at wordpress.org
Mon Sep 30 17:05:40 UTC 2024


#62136: Interactivity API: Allow reading element attributes inside derived state
props
--------------------------------------+------------------------------
 Reporter:  darerodz                  |       Owner:  czapla
     Type:  feature request           |      Status:  closed
 Priority:  normal                    |   Milestone:  Awaiting Review
Component:  Interactivity API         |     Version:  trunk
 Severity:  normal                    |  Resolution:  fixed
 Keywords:  has-patch has-unit-tests  |     Focuses:
--------------------------------------+------------------------------
Changes (by czapla):

 * owner:  (none) => czapla
 * status:  new => closed
 * resolution:   => fixed


Comment:

 In [changeset:"59131" 59131]:
 {{{
 #!CommitTicketReference repository="" revision="59131"
 Interactivity API: Add `wp_interactivity_get_element()` function.

 Introduces the `wp_interactivity_get_element()` function to the
 Interactivity API, analogous to the `getElement()` function in the
 `@wordpress/interactivity` JavaScript module. This function allows access
 to the current element being processed during directive processing.

 The function returns an array containing the `attributes` property, which
 includes only the originally defined attributes present on the element.
 Attributes added or modified by directive processing are not included.
 This is intended for use in derived state properties inside
 `wp_interactivity_state()`, similar to how
 `wp_interactivity_get_context()` is used.

 Example usage:

 ```php
 wp_interactivity_state( 'myPlugin', array(
     'buttonText' => function() {
         $context = wp_interactivity_get_context();
         $element = wp_interactivity_get_element();
         return isset( $context['buttonText'] )
           ? $context['buttonText']
           : $element['attributes']['data-default-button-text'];
     },
 ) );
 ```

 Includes unit tests to cover the new functionality.

 Props darerodz, swissspidy, cbravobernal, czapla.
 Fixes #62136.
 }}}

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/62136#comment:2>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list