0

I've found a tutorial http://www.makeuseof.com/tag/how-to-create-wordpress-widgets/ that shows how to create a basic WP Widget with a title field.

Can anyone help me add two more fields to the Widget so I can collect:

  • Title
  • Content
  • A Link

I think I then know how to use this and style it.

Help much appreciated!

Dvent

dvent
  • 105
  • 1
  • 6
  • 17

2 Answers2

4

Code to add to your file

If you want to add a textarea for content you can put the following lines into function form($instance):

printf(
    '<textarea class="widefat" rows="16" cols="20" id="%1$s" name="%2$s">%3$s</textarea>',
    $this->get_field_id( 'content' ),
    $this->get_field_name( 'content' ),
    $content
);

Where $content is the content you inserted before.

For a textfield you can you can put the following lines into the samen function:

printf( '<p>
        <label for="%1$s">%2$s</label>
        <input class="widefat" id="%1$s" name="%3$s" type="text" value="%4$s" />
    </p>',
    $this->get_field_id( 'link' ),
    __( 'Title:', $this->language ),
    $this->get_field_name( 'link' ),
    esc_attr( $link )
);

Where $link is the content you inserted before.

Add the following lines into function update($new_instance, $old_instance):

$instance['content'] = $new_instance['content'];
$instance['link']    = $new_instance['link'];

Add the following lines into function widget($args, $instance):

$content = empty( $instance['content'] ) ? '' : wpautop( $instance['content'] );
$link    = empty( $instance['link'] ) ? '' : esc_attr( $instance['link'] );

if ( ! empty( $content ) )
    echo $content;

if ( ! empty ( $link ) )
    echo "<a href='$link'>$link</a>";

If you don't want to automaticly add <p>'s to your content, simply remove wpautop.

What the functions do

function form($instance) shows the back-end widget form
function update($new_instance, $old_instance) sanitizes widget form values as they are saved.
function widget($args, $instance) shows the front-end display of widget

So if you want to alter the display of widgets settings window, edit the content of function form($instance).

Hope it helps!

Mike Madern
  • 373
  • 2
  • 9
  • Thanks Mike! How would I add additional fields (just ). Also, which part of the code defines the list they're shown in the Widget settings window? – dvent Dec 12 '12 at 15:52
0

Thanks very much for the help, Had a small issue: when you save the contents, all the contents dissapear from the form. so I fixed like this parsing the new fields on the beginning of the : $instance array

function form($instance)
    {
    $instance = wp_parse_args( (array) $instance, array( 
        'title' => '',
        'bannertext' => '',
        'link' => '' 
    ) );
    $title = $instance['title'];
    $bannertext = $instance['bannertext'];
    $link  = $instance['link'];

Then make the printf() contents