Build a custom WordPress widget with reliable update logic
A custom WordPress widget is often the cleanest way to add a reusable panel without altering a theme’s templates. The Widgets API keeps registration, administration, storage, and front-end rendering in separate methods, so a site owner can manage several copies of the same component. That separation also gives plugin developers a stable path for adding fields later without rewriting the template layer.
Building a custom WordPress widget with the Widgets API and update logic means deciding what each widget instance must store before writing any markup. A compact notice panel works well for announcements, support links, or a call to action, and it exercises the same lifecycle used by built-in widgets while remaining small enough to maintain. Content owners can then make changes without editing templates or deployment files.
Define the widget contract and data model
Start with a clear data contract. The Widgets API stores each instance separately, even when several copies appear in the same sidebar. A small notice panel might need a title, message, button label, destination URL, and a switch controlling the button. One schema should drive validation, the form, and output so each layer understands the same values.
Keep the contract narrow. A title can be empty so the theme supplies its own heading, while a message may contain basic paragraphs. Treat the button label and URL as one optional unit. If the widget will eventually be replaced by a block, preserving the same fields and sanitisation rules makes the migration less disruptive. Validate referenced content at render time too, because a linked post may later be deleted.
Australian projects add useful constraints. Use Australian English in interface copy—customise rather than customize—and day-month-year dates where appropriate. For stores, a promotional panel may need to respect Australian dollars, the 10% GST, and payment choices such as Afterpay, Stripe, and PayPal. Local client language is usually friendly but direct: “We’ll sort it out” fits a service notice better than exaggerated marketing jargon.
Register the widget with WordPress
Place the class in a small plugin, preferably one file for a focused widget. The constructor supplies a stable ID base, a translated name, and a description. The ID base becomes part of the WordPress option key, so changing it after release can make existing settings appear to vanish. Keep the constructor free of database calls; it only registers the widget and its options.
final class WP_QA_Site_Notice_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'wp_qa_site_notice',
__( 'Site notice', 'wp-qa-site-notice' ),
array(
'description' => __( 'Displays a short notice with an optional link.', 'wp-qa-site-notice' ),
'customize_selective_refresh' => true,
)
);
}
}
add_action(
'widgets_init',
static function () {
register_widget( 'WP_QA_Site_Notice_Widget' );
}
);
Register the class after WordPress loads the plugin. The widgets_init hook fires early enough for the class to appear under Appearance and then Widgets, as well as in any classic widget area exposed by the active theme. Passing the class name is concise; an instantiated object works too when the constructor needs arguments.
Use a namespace or a distinctive class prefix to avoid collisions with another plugin. Load text-domain translations, support selective refresh in the Customizer, and avoid closing the PHP tag in a pure PHP plugin file. Version the stored schema if later releases add fields, and migrate old values deliberately.
Render safe, theme-friendly output
Override widget() to define what visitors see. Read values from the instance, but use the theme-provided wrappers for the surrounding region and heading. The method should work with defaults so a newly added widget does not emit notices for missing settings. Avoid uncached queries here, since several sidebar copies should not repeat the same request.
public function widget( $args, $instance ) {
$title = apply_filters(
'widget_title',
$instance['title'] ?? '',
$instance,
$this->id_base
);
$message = $instance['message'] ?? '';
$show_cta = ! empty( $instance['show_cta'] );
$button_text = $instance['button_text'] ?? '';
$button_url = $instance['button_url'] ?? '';
echo $args['before_widget'];
if ( '' !== $title ) {
echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
}
if ( '' !== $message ) {
echo '<div class="site-notice">' . wp_kses_post( wpautop( $message ) ) . '</div>';
}
if ( $show_cta && '' !== $button_text && '' !== $button_url ) {
echo '<p class="site-notice__action"><a href="' .
esc_url( $button_url ) . '">' . esc_html( $button_text ) .
'</a></p>';
}
echo $args['after_widget'];
}
The $args array supplies before_widget, after_widget, and title wrappers from the active theme. Using them keeps spacing and heading markup under theme control. The widget_title filter also preserves standard WordPress behaviour, including translations and plugins that decorate widget headings. Rebuilding wrappers inside the widget prevents themes from controlling classes and accessibility.
Escape at output even though update-time cleaning already ran. esc_html() protects plain text, esc_url() protects the link, and wp_kses_post() permits only safe post markup in the message. Cache-friendly output contains no nonce, timestamp, or request-specific value, so page caching remains predictable. Use the plugin’s text domain for translated interface strings.
Build an accessible widget form
The form method renders fields for one widget instance. Use get_field_id() and get_field_name() so labels, uniqueness, and the array-shaped field names required by the Widgets API remain correct. Group related controls with fieldsets if the form grows, and keep every input labelled.
public function form( $instance ) {
$title = $instance['title'] ?? '';
$message = $instance['message'] ?? '';
$button_text = $instance['button_text'] ?? '';
$button_url = $instance['button_url'] ?? '';
$show_cta = ! empty( $instance['show_cta'] );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
<?php esc_html_e( 'Title', 'wp-qa-site-notice' ); ?>
</label>
<input class="widefat" type="text"
id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
value="<?php echo esc_attr( $title ); ?>">
</p>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'message' ) ); ?>">
<?php esc_html_e( 'Message', 'wp-qa-site-notice' ); ?>
</label>
<textarea class="widefat" rows="5"
id="<?php echo esc_attr( $this->get_field_id( 'message' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( 'message' ) ); ?>"><?php echo esc_textarea( $message ); ?></textarea>
</p>
<p>
<input type="checkbox"
id="<?php echo esc_attr( $this->get_field_id( 'show_cta' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( 'show_cta' ) ); ?>"
value="1" <?php checked( $show_cta ); ?>>
<label for="<?php echo esc_attr( $this->get_field_id( 'show_cta' ) ); ?>">
<?php esc_html_e( 'Show call to action', 'wp-qa-site-notice' ); ?>
</label>
</p>
<?php
}
The generated names look like widget-wp_qa_site_notice[2][title], where 2 identifies the instance. Do not replace them with hard-coded names. The Widgets screen already enforces administrator capability and nonce protection; a widget form does not need a second nonce. An unchecked checkbox sends no value, which explains the special handling in update(). A mistyped field name silently creates a value that update() will never receive.
Keep labels explicit and mark only the title as optional in the description. The CTA URL should use a url input, but server-side validation remains authoritative because imported data or a custom request can bypass browser checks. Keep explanatory text outside input values and translate it with the rest of the panel.
Implement dependable update logic
update() receives submitted values as $new_instance and previous values as $old_instance, and it must return the complete array to store. Merge old values so a partial programmatic update can preserve omitted text fields, but treat an absent checkbox as false because an unticked HTML checkbox is never posted. Saving identical values twice should therefore produce an identical array.
public function update( $new_instance, $old_instance ) {
$new_instance = is_array( $new_instance ) ? $new_instance : array();
$old_instance = is_array( $old_instance ) ? $old_instance : array();
$title = $new_instance['title'] ?? $old_instance['title'] ?? '';
$message = $new_instance['message'] ?? $old_instance['message'] ?? '';
$button_text = $new_instance['button_text'] ?? $old_instance['button_text'] ?? '';
$button_url = $new_instance['button_url'] ?? $old_instance['button_url'] ?? '';
return array(
'title' => is_scalar( $title ) ? sanitize_text_field( (string) $title ) : '',
'message' => is_scalar( $message ) ? sanitize_textarea_field( (string) $message ) : '',
'button_text' => is_scalar( $button_text ) ? sanitize_text_field( (string) $button_text ) : '',
'button_url' => is_scalar( $button_url ) ? esc_url_raw( (string) $button_url ) : '',
'show_cta' => ! empty( $new_instance['show_cta'] ),
);
}
Returning an array is important: WordPress serialises it under widget_wp_qa_site_notice and keys each copy by its instance number. Avoid calling update_option() inside this method, because that can overwrite other widget instances or race with the core save process. The sanitiser also creates a safe boundary for settings supplied by migrations or custom admin screens. Never treat widget options as a secret vault; exports and database tools can expose their contents.
For programmatic changes, run the values through the widget’s update() method and pass the result to wp_update_instance( $instance_number, 'wp_qa_site_notice', $clean_values ). If a custom endpoint appears to hang while saving, separate server and network failures before changing widget code; this guide to fixing REST timeouts covers useful timeout checks. Log the instance number and outcome on failure, but not message bodies or personal details.
Test and operate the widget in production
Test the widget in staging before it reaches a production sidebar. Check the classic Widgets screen and any widget area exposed by the active theme, then repeat the same actions after saving. The same instance must keep its own settings when it is moved, duplicated, reordered, or removed. Repeat the workflow in current Chrome, Safari, and Firefox, including a keyboard-only check.
Run these behaviour checks in staging:
- Add two instances with different content and confirm one save does not alter the other.
- Clear a title and message, then save and reload to verify empty values are intentional.
- Toggle the CTA off and confirm the previous label and URL no longer render.
- Switch themes and check the widget wrappers, spacing, and keyboard focus.
Deployment checks should reflect Australian operating conditions:
- Test from Sydney, Melbourne, Brisbane, and Perth, and account for AEST/AEDT plus states without daylight saving when notices are scheduled.
- On WooCommerce sites, verify AUD amounts, 10% GST messaging, and payment methods such as Afterpay, Stripe, and PayPal.
- Review collected personal information against the Privacy Act 1988 and Australian Privacy Principles, using ACSC guidance where needed.
- Require HTTPS, limit admin access, and exclude notice text from public logs when it may contain customer details.
Core can then handle persistence while the plugin owns validation and output. Each instance remains independent, the theme retains control of placement, and administrators can update the notice without touching templates or deployment files. Document the ID base and expected fields so later releases can migrate them safely.