Skip to content

Instantly share code, notes, and snippets.

@krystyna93
Last active June 10, 2023 12:55
Show Gist options
  • Save krystyna93/dcdbbed6955e5e9b2d26b9b5e725b242 to your computer and use it in GitHub Desktop.
Save krystyna93/dcdbbed6955e5e9b2d26b9b5e725b242 to your computer and use it in GitHub Desktop.
Custom WordPress Widget Example: Greetings message w/strip_tags() and isset()
<?php
class birdtree_greeting_widget extends WP_Widget {
// Set up the widget name, description, etc.
public function __construct() {
$widget_options = array(
'classname' => 'birdtree_greeting_widget',
'description' => 'Displays a greeting message from BirdTree'
);
parent::__construct( 'birdtree_greeting_widget', 'BirdTree Greeting Widget', $widget_options );
}
// Output the contents of the widget
public function widget( $args, $instance ) {
echo $args['before_widget'];
// Apply filters to the widget title
$title = apply_filters( 'widget_title', isset( $instance['title'] ) ? $instance['title'] : '' );
if ( ! empty( $title ) ) {
echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
}
// Display the greeting message
echo '<p>' . esc_html__( 'Greetings, from BirdTree!', 'birdtree' ) . '</p>';
echo $args['after_widget'];
}
// Output the options form on admin
public function form( $instance ) {
// Retrieve the previously saved values
$title = isset( $instance['title'] ) ? $instance['title'] : '';
// Output the form fields
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'birdtree' ); ?></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>
<?php
}
// Sanitize and validate the widget options
public function update( $new_instance, $old_instance ) {
$instance = array();
// Sanitize the title field
$instance['title'] = isset( $new_instance['title'] ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
/*
This code uses strip_tags() to remove any HTML tags from the widget title field in the update() method.
This helps prevent against potential XSS attacks by ensuring that any HTML code entered into the field is stripped out before
the data is saved to the database.
also checks if the title field is set using isset() in both the widget() and form() methods.
If the field is not set, it defaults to an empty string. This ensures that the code will not generate any PHP warnings or errors
when the widget is used without a title.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment