J
J
jurvrn2020-07-05 16:15:08
WordPress
jurvrn, 2020-07-05 16:15:08

What's wrong with displaying the title of a Wordpress widget by default?

When inserting a widget title, the error "Notice: Undefined index: title in /home/*****/vkalendar_php.php on line 42" is displayed.
Line 42 is: $title = apply_filters('widget_title', $instance['title']);
Although the default widget name is given as "Specify Widget Title".
The main code for generating a widget

class my_widget_plugin_vk_php extends WP_Widget
{
    function __construct()
    {
        parent::__construct(
            'my-widget-plugin-vk-php',
            'Календарь по годам (виджет) на php',
            array('description' => 'Выводит таблицу календаря на php (виджет)',)
        );
    }

    public function form($instance)
    {
        if (isset($instance['title'])) {
            $title = $instance['title'];
        } else {
            $title = 'Укажите заголовок виджета';
        }
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
                   name="<?php echo $this->get_field_name('title'); ?>" type="text"
                   value="<?php echo esc_attr($title); ?>"/>
        </p>
        <?php
    }

    public function widget($args, $instance)
    {
        $title = apply_filters('widget_title', $instance['title']); //ЗДЕСЬ 42 СТРОКА С ОШИБКОЙ
        echo $args['before_widget'];
        if (!empty($title))
            echo $args['before_title'] . $title . $args['after_title'];

echo <<<HTML
............
HTML;
      echo $args['after_widget'];
    }

    public function update($new_instance, $old_instance)
    {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        return $instance;
    }
}

function my_widget_plugin_vk_load_php() {
    register_widget('my_widget_plugin_vk_php');
}

add_action('widgets_init', 'my_widget_plugin_vk_load_php');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Thes, 2020-07-08
@Thes

Checked, there is no such error.
And yes, use a simpler check:
$title = isset( $instance['title'] ) ? $instance['title'] : 'Specify a title for the widget';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question