0
    $title = isset( $instance['title'] ) ? $instance['title'] : '';

and

        $title               = strip_tags($instance['title']);

what is the difference between the above two?

Do they perform the one and the same action in the widget form method? Or I am mistaking something as they have different functions or one is used in widget form function and the another one is used in the widget's widget method?

Or they just the difference of coding practice?

Or if they are performing the same action then we can combine them and make a better fusion like this →

$title = isset( $instance['title'] ) ? strip_tags($instance['title']) : '';

Please also help me to understand what is the role of this here → ?

1 Answer 1

1

It is just a PHP coding practice difference and you can combine both. The use of ?: is called ternary operator and it is like a if/else shorthand. This line:

 $title = isset( $instance['title'] ) ? $instance['title'] : '';

It is like:

if( isset( $instance['title'] ) ) {
    $title = isset( $instance['title'] );
} else {
    $title = '';
}

If you see core widgets, they usually use the ternary operator, but is just a coding preference. For example, you can see this code in Archives widget:

$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Archives' ) : $instance['title'], $instance, $this->id_base );

Or this one in Calendar widget:

$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );

Applying the widget_title it is more important to me than using or not ternary operators; you shouldn't forget it.

2
  • Sir, Can you please elaborate over this with an example → Applying the widget_title it is more important to me than using or not ternary operators; you shouldn't forget it.
    – WordCent
    Commented May 8, 2017 at 17:09
  • 1
    There are examples in the answer already ; see the apply_filters( 'widget_title', ...) part. By applying widget_title filter, any other developer can filter the widget's title if needed, but of course is optional, it is just a way to provide flexibility but not a requirement for a widget to work.
    – cybmeta
    Commented May 8, 2017 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.