A Web Component for the WordPress admin: a star rating input
A plugin that needs the same small widget on three admin screens (a meta box, the user profile, a settings page) usually copies jQuery code three times. A Custom Element is defined once in a plain JavaScript file and then used like an HTML tag: <ha-star-rating name="..." value="3">. No build step, no framework, and it works inside any form.
Problem: A plugin shows a star rating input in a post meta box, on the user profile and on its settings page. Each screen has its own copy of the markup and the jQuery code, and a fix on one screen is forgotten on the others.
Solution: Define a <ha-star-rating> Custom Element that renders its buttons in a Shadow DOM, keeps its value in a hidden input in the light DOM so that the normal form submit sends it, reacts to the value attribute, and is keyboard accessible as a radio group. Enqueue the file on the three screens and sanitize the value in PHP as usual.
The element
// js/star-rating.js
const template = document.createElement( 'template' );
template.innerHTML = `
<style>
:host { display: inline-flex; gap: .125rem; }
button { all: unset; cursor: pointer; font-size: 1.5rem; line-height: 1; color: #c3c4c7; }
button[aria-checked="true"], button.preview { color: #dba617; }
button:focus-visible { outline: 2px solid #2271b1; outline-offset: 2px; }
</style>
<div role="radiogroup" part="group"></div>
`;
class HaStarRating extends HTMLElement {
static observedAttributes = [ 'value' ];
#input;
#buttons = [];
constructor() {
super();
this.attachShadow( { mode: 'open' } ).append( template.content.cloneNode( true ) );
}
connectedCallback() {
if ( this.#input ) return; // moved in the DOM, already set up
const max = Number( this.getAttribute( 'max' ) ) || 5;
const group = this.shadowRoot.querySelector( '[role="radiogroup"]' );
group.setAttribute( 'aria-label', this.getAttribute( 'label' ) ?? 'Rating' );
this.#input = Object.assign( document.createElement( 'input' ), {
type: 'hidden',
name: this.getAttribute( 'name' ) ?? '',
} );
this.append( this.#input );
for ( let i = 1; i <= max; i++ ) {
const button = document.createElement( 'button' );
button.type = 'button';
button.textContent = '★';
button.setAttribute( 'role', 'radio' );
button.setAttribute( 'aria-label', `${ i } of ${ max }` );
button.addEventListener( 'click', () => { this.value = i; } );
button.addEventListener( 'mouseenter', () => this.#preview( i ) );
button.addEventListener( 'mouseleave', () => this.#preview( 0 ) );
group.append( button );
this.#buttons.push( button );
}
group.addEventListener( 'keydown', ( event ) => {
const step = { ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1 }[ event.key ];
if ( ! step ) return;
event.preventDefault();
this.value = Math.min( max, Math.max( 1, this.value + step ) );
this.#buttons[ this.value - 1 ].focus();
} );
this.#render();
}
attributeChangedCallback() {
this.#render();
}
get value() {
return Number( this.getAttribute( 'value' ) ) || 0;
}
set value( v ) {
this.setAttribute( 'value', String( v ) );
this.dispatchEvent( new Event( 'change', { bubbles: true } ) );
}
#render() {
if ( ! this.#input ) return;
const value = this.value;
this.#input.value = value || '';
this.#buttons.forEach( ( button, index ) => {
const checked = index + 1 <= value;
button.setAttribute( 'aria-checked', String( index + 1 === value ) );
button.classList.toggle( 'preview', checked );
button.tabIndex = index + 1 === ( value || 1 ) ? 0 : -1;
} );
}
#preview( upTo ) {
const limit = upTo || this.value;
this.#buttons.forEach( ( button, index ) => button.classList.toggle( 'preview', index < limit ) );
}
}
if ( ! customElements.get( 'ha-star-rating' ) ) {
customElements.define( 'ha-star-rating', HaStarRating );
}
The parts that are easy to get wrong:
- The shadow root is created in the constructor, the content in
connectedCallback(), which runs again every time the element is moved in the DOM; the guard at the top prevents a second set of buttons. - An input inside a Shadow DOM is not part of the surrounding form. The hidden input is therefore appended to the element itself (light DOM), and the normal POST of the meta box or settings form sends it.
- The buttons form a radio group for screen readers:
role="radio",aria-checked, one button in the tab order, arrow keys to change the value. - The element name must contain a hyphen, and the prefix
ha-avoids a collision with another plugin’sstar-rating.customElements.define()throws if the name is already taken, hence the check.
Use it in a meta box
add_action( 'admin_enqueue_scripts', 'ha_star_rating_script' );
function ha_star_rating_script( string $hook ): void {
if ( in_array( $hook, array( 'post.php', 'post-new.php', 'profile.php', 'user-edit.php', 'settings_page_ha-settings' ), true ) ) {
wp_enqueue_script( 'ha-star-rating', plugins_url( 'js/star-rating.js', __FILE__ ), array(), '1.0.0', true );
}
}
function ha_rating_meta_box( WP_Post $post ): void {
wp_nonce_field( 'ha_save_rating', 'ha_rating_nonce' );
printf(
'<ha-star-rating name="ha_rating" value="%d" label="%s"></ha-star-rating>',
(int) get_post_meta( $post->ID, '_ha_rating', true ),
esc_attr__( 'Editor rating', 'textdomain' )
);
}
add_action( 'save_post', 'ha_save_rating' );
function ha_save_rating( int $post_id ): void {
if ( ! isset( $_POST['ha_rating_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['ha_rating_nonce'] ), 'ha_save_rating' ) ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$rating = min( 5, absint( $_POST['ha_rating'] ?? 0 ) );
update_post_meta( $post_id, '_ha_rating', $rating );
}
The meta box itself is registered with add_meta_box() as usual: a custom meta box with secure save handling. The server never trusts the value from the element and clamps it to 0–5.
NOTE: Custom Elements, Shadow DOM, private class fields (#input) and static class fields work in all browsers that the WordPress admin supports. The alternative to the hidden input is a form-associated custom element with ElementInternals and setFormValue(), which Safari supports only since version 16.4 (March 2023); the hidden input works everywhere and is simpler to debug.