I have an issue with custom widgets and WordPress Coding Standards. When you create a custom widget, your class should have a “widget” method that will display the widget. Something like:

<?php
public function widget( $args, $instance ) {
    echo $args['before_widget'];
    ?> <span><?php echo esc_html( 'Great widget', 'text-domain' ); ?></span> <?php
    echo $args['after_widget'];
}
?>

While this is perfectly functional, this will not pass PHP code sniffer tests with WordPress coding standards because $args['after_widget']; and $args['before_widget']; are not escaped…

What am I doing wrong?

2 Answers
2

These arguments contain arbitrary HTML and cannot be properly escaped. This is essentially a limitation on how Widgets code was designed and you can see in core Widget classes that no escaping is done on these.

Lessons to learn:

  • WP core doesn’t consistently adhere to its own coding standards (and getting there isn’t considered worth targeted effort);
  • passing around chunks of HTML is bad idea, in your own code pass data and render appropriately with proper escaping.

Leave a Reply

Your email address will not be published. Required fields are marked *