0

I'm trying to get my head around writing custom widgets with options. I've been following a few tutorials and have been trying to understand as I go.

I've got a widget that works perfectly in the Widgets manager, but on the front end I get Undefined variable: image_path. I can't track down what I've done wrong and would definitely appreciate another set of eyes.

Widget code:

/* Image Link Widget
===================================================== */
class ImageLinkWidget extends WP_Widget {

  function ImageLinkWidget() {
    $widget_ops = array(
      'classname' => 'google-map-widget nopadding',
      'description' => 'An image that links somewhere'
    );
    $this->WP_Widget('ImageLinkWidget', 'Image + Link', $widget_ops);
  }

  function form($instance) {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'image_path' => 'default' ) );
    $title = $instance['title'];
    $image_path = $instance['image_path']
    ?>
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title: 
          <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); ?>" />
        </label>
      </p>
      <p>
        <label for="<?php echo $this->get_field_id('image_path'); ?>">
          Image Path (include http://): 
          <input class="widefat" id="<?php echo $this->get_field_id('image_path'); ?>" name="<?php echo $this->get_field_name('image_path'); ?>" type="text" value="<?php echo esc_attr($image_path); ?>" />
        </label>
      </p>
    <?php
  }

  function update($new_instance, $old_instance) {
    $instance = $old_instance;
    $instance['title'] = strip_tags( $new_instance['title'] );
    $instance['image_path'] = strip_tags( $new_instance['image_path'] );
    return $instance;
  }

  function widget($args, $instance) {
    extract($args, EXTR_SKIP);

    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

    if (!empty($title))
      echo $before_title . $title . $after_title;

    // Show image plus link
    //echo '<a href="' . $link . '" target="' . $target . '">';
      //echo '<img src="' . $image_path . '" alt="' . $alt_text . '">';
      echo $image_path;
    //echo '</a>';

    echo $after_widget;
  }

}
add_action( 'widgets_init', create_function('', 'return register_widget("ImageLinkWidget");') );

Thanks in advance!

1 Answer 1

2

You need to use $instance['image_path'], or extract $instance (I prefer the former).

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.