Building a Widget: Part 4

Ok, so a day or two ago I worked through the widget options and the first basic widget section, called the constructor. The middle section of the widget defines how WP handles updates to the widget. We are updating the instance of the widget we saved before.

Mine looks like this:

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

This part is actually pretty straightforward. This uses the inputs from the form we will build next to save info to a new widget instance. This is also how variables get passed to the constructor we built in the first sections.

The third section is the form that a user will see when they are using the widget on the back end, so this is where all of your options will be. If you have no options for your widget, then you should probably just put a nice little note here explaining what you widget does. For my widget I have 4 fields, the first is widget title, then the text to be displayed, and then the link text and URL. Like I said, this would be simple to output in the existing Text widget, but the goal is to remove any need to code anything so my clients can easily use this.

 function form($instance) {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'text' => '', 'link_url' => '', 'link_text' => '' ) );
    $title = strip_tags($instance['title']);
    $text = strip_tags($instance['text']);
    $link_url = strip_tags($instance['link_url']);
    $link_text = strip_tags($instance['link_text']);
    ?>
    <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 attribute_escape($title); ?>" /></label></p>
    <p><label for="<?php echo $this->get_field_id('text'); ?>">Text: <textarea class="widefat" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text"><?php echo attribute_escape($text); ?></textarea></label></p>
    <p><label for="<?php echo $this->get_field_id('link_url'); ?>">Full URL of Link: <input class="widefat" id="<?php echo $this->get_field_id('link_url'); ?>" name="<?php echo $this->get_field_name('link_url'); ?>" type="text" value="<?php echo attribute_escape($link_url); ?>" /></label></p>
    <p><label for="<?php echo $this->get_field_id('link_text'); ?>">Link Text: <input class="widefat" id="<?php echo $this->get_field_id('link_text'); ?>" name="<?php echo $this->get_field_name('link_text'); ?>" type="text" value="<?php echo attribute_escape($link_text); ?>" /></label></p>
    <?php
    }

So up top we are just setting our vars for this instance to nothing, then setting them to the input from the form we built underneath. I’m using the php strip_tags() function to remove any unwanted php or html that might booger up what I’m trying to do. That’s essentially it. The last thing we need to do is register our widget, which is done by register_widget('Promo_Tooth');.

Here’s the whole shabang.

 // Promo Widget (tooth icon) for displaying the promo box with limited options configurable by contributors

    class Promo_Tooth extends WP_Widget {
    function Promo_Tooth() {
    $widget_ops = array('classname' => 'toothPromo', 'description' => 'Displays promo box with tooth icon' );
    $this->WP_Widget('promo_tooth', 'Promo - Tooth Icon', $widget_ops);
    }
    function widget($args, $instance) {
    extract($args, EXTR_SKIP);
    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
    $text = empty($instance['text']) ? ' ' : apply_filters('widget_text', $instance['text']);
    $link_url = empty($instance['link_url']) ? ' ' : apply_filters('widget_link_url', $instance['link_url']);
    $link_text = empty($instance['link_text']) ? ' ' : apply_filters('widget_link_text', $instance['link_text']);
    if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
    echo '<img src="images/tooth.png">';
    echo '<p>' . $text . '</p>';
    echo '<a href="' . $link_url . '">';
    echo $link_text . ' &raquo;';
    echo '</a>';
    echo $after_widget;
    }
    function update($new_instance, $old_instance) {
    $instance = $old_instance;
    $instance['title'] = strip_tags($new_instance['title']);
    $instance['text'] = strip_tags($new_instance['text']);
    $instance['link_url'] = strip_tags($new_instance['link_url']);
    $instance['link_text'] = strip_tags($new_instance['link_text']);
    return $instance;
    }
    function form($instance) {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'text' => '', 'link_url' => '', 'link_text' => '' ) );
    $title = strip_tags($instance['title']);
    $text = strip_tags($instance['text']);
    $link_url = strip_tags($instance['link_url']);
    $link_text = strip_tags($instance['link_text']);
    ?>
    <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 attribute_escape($title); ?>" /></label></p>
    <p><label for="<?php echo $this->get_field_id('text'); ?>">Text: <textarea class="widefat" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" type="text"><?php echo attribute_escape($text); ?></textarea></label></p>
    <p><label for="<?php echo $this->get_field_id('link_url'); ?>">Full URL of Link: <input class="widefat" id="<?php echo $this->get_field_id('link_url'); ?>" name="<?php echo $this->get_field_name('link_url'); ?>" type="text" value="<?php echo attribute_escape($link_url); ?>" /></label></p>
    <p><label for="<?php echo $this->get_field_id('link_text'); ?>">Link Text: <input class="widefat" id="<?php echo $this->get_field_id('link_text'); ?>" name="<?php echo $this->get_field_name('link_text'); ?>" type="text" value="<?php echo attribute_escape($link_text); ?>" /></label></p>
    <?php
    }
    }
    register_widget('Promo_Tooth');

BOOM! Widget! The final product looks like this on the back end:

And with a dash of CSS, this is how it displays on the live site:

Right now I have three different widgets for three different icons. What I need to do is add a simple dropdown menu in a single widget to select which icon to display. Should be simple enough. All I will need to do is add the drop down to my menu, and add an icon var to my constructor and update sections.

Feel free to use or change this as you need. Just leave a comment and let me know if it worked for you.

jQuery Mobile Beta 1 Release


Yesterday the good people at jQuery announced the first Beta release of jQuery mobile. If you’re not already using jQuery in your development then… WAIT, WHAT?! WHY AREN’T YOU USING JQUERY?!

The mobile framework provides some dead simple ways to provide a great user experience across multiple mobile platforms. The β1 release has support for iOS 3.2+, Android 2.1+, BB 6.0, WP7, and many more. They have graded the mobile browser support, meaning that the mobile browsers listed above are supported at an "A" level, whereas Opera Mini 5.0 is supported at a "B" level. It seems as though the features will degrade gracefully to the lesser supported browsers. They have created a host of other features specifically tailored to mobile browsers.

Though just premiering as a the first beta release, still very exciting to see the fantastic jQuery framework developed specifically for mobile browsers. Sign of the time I suppose.

jQuery Mobile Beta 1 Released »

Building a Widget: Part 3

I quickly gave up working with the WordPress Codex and found what I think is a better starting point from WPengineer.com. Widgets are broken down into three basic sections. The first section is the actual widget; what it’s doing and what it’s displaying. The middle section is how the updates are handled. When you save or update the widget WP will create or update an instance of the widget, these multiple instances of the widget are what allow you display the same widget in multiple places with different settings. The third section is for control, that’s where we’ll put the form that allows the user to control the widget options in the WP backend. The very basic structure looks like this:

    class My_RSS_Widget extends WP_Widget {
    function My_RSS_Widget() {
    //Constructor
    }
    function widget($args, $instance) {
    // prints the widget
    }
    function update($new_instance, $old_instance) {
    //save the widget
    }
    function form($instance) {
    //widgetform in backend
    }
    }
    register_widget('My_RSS_Widget');

Here we can see the three major sections of a widget. Although WPengineer says "The code is self-explanatory", I certainly didn’t find it to be, so I’ll try to help out a bit. When building a widget, what we are really doing is building an extension of the WP_Widget class already built into WP which is located in wp-includes/widgets.php. So let’s start with all the stuff before the first sections starts.

class Promo_Tooth extends WP_Widget {
    function Promo_Tooth() {
    $widget_ops = array('classname' => 'toothPromo', 'description' => 'Displays promo box with tooth icon' );
    $this->WP_Widget('promo_tooth', 'Promo - Tooth Icon', $widget_ops);
    }

So Promo_Tooth is the name of my widget, and $widget_ops takes an array that contains descriptive info for your widget. classname is the class that will be added to your widget and the description is the description the user will see on the backend. $this sets all the options for the widget, including what is passed to it from $widget_ops. The first argument is the id prefix for each widget instance, in my case sometime like promo_tooth-3 (WP auto increments each instance of the widget so you can access the widget with a unique id). The second argument is the title of your widget on the WP backend, and then finally you pass all the options assigned to $widget_ops to $this.

With the above options, you get something like this in the Widgets page of your admin panel.

Ok, so now to the first section of the widget code:

function widget($args, $instance) {
    extract($args, EXTR_SKIP);
    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
    $text = empty($instance['text']) ? ' ' : apply_filters('widget_text', $instance['text']);
    $link_url = empty($instance['link_url']) ? ' ' : apply_filters('widget_link_url', $instance['link_url']);
    $link_text = empty($instance['link_text']) ? ' ' : apply_filters('widget_link_text', $instance['link_text']);
    if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };
    echo '<img src=".../images/tooth.png">';
    echo '<p>' . $text . '</p>';
    echo '<a href="' . $link_url . '">';
    echo $link_text . ' &raquo;';
    echo '</a>';
    echo $after_widget;
    }

So this is where the actual work is being done. For my widget this is fairly simple because I am simply displaying information the user has input into the widget form on the backend. The purpose of this widget is to remove all need to add any actual code to achieve a very specific and limited output. The extract function imports the vars in the array to the current symbol table, and the EXTR_SKIP argument tells the function not to overwrite duplicate vars. $before_widget and $after_widget are vars that set how your widgets display in the sidebar, there’s a good explanation of them in the WP Codex. The same is true for $before_title and $after_title. These are usually li or h2 tags that control the display and layout of widgets within the theme. Make sure you are using these or your layout will be completely messed up. You can always override the display of an element using CSS.

Then all we are doing is defining our vars for use in the output, the vars will be set later by user input in the form section, after our vars are defined we can simply echo the desired output. This is a simple case obviously, because all we are doing is outputting user inputted strings with a little extra HTML around it. But this is where you would put whatever function you would like to perform before displaying data. So after you are done echoing, just make sure you echo $after_widget to append your closing li tags (or whichever tag your theme uses to organize a sidebar or widget area).

I think that’s enough for now, I’ll tackle the rest of the widget tomorrow.

Building a Widget: Part 2

Last week I said I needed to make a fairly simple widget for a client site built on WordPress. The purpose of the widget is to basically to replicate the functionality of the “Text” widget that comes standard with WordPress, then add a couple of extra little bits of functionality to it. Granted, this could all be done using the Text widget, I want my clients to be able to add/remove/change the widget without needing any ability to code.

Getting Started
Anytime I’m doing something a little over my head I try to find an example that closely replicates what I am trying to achieve and play around with it to try and get an understanding of what’s going on under the hood. Fortunately WordPress has the codex, and in their widgets codex they have a nice little sample widget. The code of which is this:

/**
/**
 * FooWidget Class
 */
class FooWidget extends WP_Widget {
    /** constructor */
    function FooWidget() {
        parent::WP_Widget(false, $name = 'FooWidget');
    }

    /** @see WP_Widget::widget */
    function widget($args, $instance) {
        extract( $args );
        $title = apply_filters('widget_title', $instance['title']);
        ?>
              <?php echo $before_widget; ?>
                  <?php if ( $title )
                        echo $before_title . $title . $after_title; ?>
                  Hello, World!
              <?php echo $after_widget; ?>
        <?php
    }

    /** @see WP_Widget::update */
    function update($new_instance, $old_instance) {
	$instance = $old_instance;
	$instance['title'] = strip_tags($new_instance['title']);
        return $instance;
    }

    /** @see WP_Widget::form */
    function form($instance) {
        $title = esc_attr($instance['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 $title; ?>" />
        </p>
        <?php
    }

} // class FooWidget

The code above should be added to the end of functions.php within your theme’s directory, I think… It seems to work, then add this snippet after to register your widget:

// register FooWidget widget
add_action('widgets_init', create_function('', 'return register_widget("FooWidget");'));

And after doing all this, when you go to your widgets panel from the admin section you should see the FooWidget available and when you add it to an active sidebar you’ll see an options panel that looks a little like this;

Note that I am using the Widget Logic plugin to limit the display of widgets on pages using the WordPress Conditional Tags. So you won’t see the form field for “Widget Logic” without the plugin installed.

Anyway, everything seems to be in order. Let’s see about changing the widget’s name. This is done by simply changing the class, which is by the way all an extension of the built in WP_Widget class, which is located in wp-includes/widget.php. That was easy enough.. make sure you change all instances of the function() calls as well as the variable definitions.

The title field seems to work just as I wanted in my widget, so I’ll leave that be. I do need to add a textarea field for a small amount of copy text to be displayed in the widget under the title. Let’s see about that. My guess is I can do that by extending the WP_Widget’s form, so let’s add this and see what we get:

 <p>
         <label for="PW_copy"><?php echo 'Body Text'; ?></lablel>
         <input class="widefat" rows="16" cols="20" id="PW_copy" name="PW_copy" type="textarea" value="" />
        </p>

I’m missing a ton of php here that will dynamically add the id and name attributes, and I haven’t defined a new instance of the widget to save the text copy. This is kind of annoying.

I guess that’s enough for one post. This is where I’ll leave it for now:

I’ll be back tomorrow with hopefully some leaps and bounds of progress.

Building a Widget

So for the first time I find myself needing to build a simple widget for WordPress. I figured I should document the journey here (mostly because 3 months from now I’ll forget it all and have to look back here).

This widget has 3 basic elements:

  1. A title
  2. A text field
  3. Radio buttons to select from a variety of icons to display adjacent to the title.

Why not just use the built in “Text” widget? Well, this is for a client site, and for ease of use I would like them to be able to quickly and easily change some simple options (without the need to know and HTML) and achieve the desired result.

I’ll be using the sample widget found at http://codex.wordpress.org/Widgets_API as a starting point.

So come with me and let’s build a widget… Let’s start tomorrow though…

WP Custom Login Screen

The more I use WordPress the more easily I can pick out other sites that use it. I frequently catch myself appending /wp-admin/ to the URL to see if it’s a WP powered site. But what kills me, especially if it’s fairly obvious that the site has been created by a third party developer, is leaving the WP default login screen alone.

I’m a big believer that the devil is in the details, and if you can spend literally less than 5 minutes and create a custom login screen for your client, why wouldn’t you?

It’s fairly easy to apply some CSS and edit the default page, but what I find is the easiest way is to make use of the fantastically simple and effective BM Custom Login plugin from Binary Moon. By default, you’ll get something like this:

 

Now, using BM Custom Login is a lot easier if you have Photoshop so you can make use of the included .psd template, but even without it, you can create a .jpg with the same dimensions, and then you can get a customized login screen that looks something more like this:

 

It take less than 5 minutes, and it might just make the difference in whether or not your client recommends you. After all, we are building sites for our clients right. Let’s at least make it look like we went a little beyond plugging their content into an off-the-shelf WP theme.

 

Coda

I have tried out dozens of different applications and platforms for web development, and the one I always come back to is Coda by Panic.

Coda is the best I’ve found at providing a robust enough development environment while still keeping things clean and simple. It’s not for the WYSIWIG people. This if for people who are actually coding. It provides great syntax highlighting for a number of different languages. It’s clean and simple interface does a great job at managing multiple sites, which is great if you’re working on more than one project at a time, but less useful if you primarily work on just one.

It has support for subversion, which is fantastic if you’re editing with others, and it supports plug-ins.

Anyway, if you’re looking for a good platform, Coda is a great place to start. It’s $99, but you can try it out for a while before you buy.

Dont’ Forget the Favicon

The two most common situations I get hired in are (1) when a client has tried, and failed, to build their own site and (2) when a client has hired a dev to build a site and it turns out to be a real P.O.S. Sure, there’s plenty of mess to clean up in both situations, but I think the thing that irks me the most is when people just plain don’t use a favicon. WHY?! The favicon is displayed by almost every modern browser and if your user wants to add a bookmark to your site it provides them with and instantly recognizable visual cue as to what they’re clicking on or which tab your site in open in.

I’m sure you’re already using a favicon, but if you’re not, here is the ONE LINE of code you need:

<link rel="shortcut icon" href="path/to/the_icon/favicon.ico" />

Cart before the horse? Yeah, guess so. So, how do you make a favicon? Well, www.favicon.cc/ is a very good place to start, especially if you’re without a more robust image editor on your PC. Once you’ve downloaded your favicon upload it to the top level directory in your site and be sure that href="path/to/the_icon/favicon.ico" is set to the location of the actual icon.

Rant over.

WordPress, Facebook, and OpenGraph

If you’re looking to add a little social media integration to your WordPress blog then their Dev center docs on Open Graph are a good place to start. They’re essentially a way to pass along information about your site to Facebook, so when a visitor on your site clicks a "Like" button the information in your Open Graph <meta> tags is passed to Facebook and the right information gets displayed.

If you don’t use the Open Graph meta tags you leave it up to Facebook to try and extract the information all on its own, and it may or not be what you want displayed. So the best option is to use the Open Graph <meta> tags and be sure you’re sending the right info.

Your Open Graph tags might look something like this:

 <meta property="og:title" content="The Rock"/>
    <meta property="og:type" content="movie"/>
    <meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
    <meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
    <meta property="og:site_name" content="IMDb"/>
    <meta property="fb:admins" content="USER_ID"/>
    <meta property="og:description"
          content="A group of U.S. Marines, under command of
                   a renegade general, take over Alcatraz and
                   threaten San Francisco Bay with biological
                   weapons."/>

That’s the example straight from Facebook. What you’re doing is telling Facebook about your page so they don’t have to figure it out themselves. But the problem is with the og:type, because the front page of your blog probably has a type of either blog or website, which is fine. But if you would like to share any of your posts individually, they should have a content type of article to represent it’s transient nature.

So you will need to pass a different set of Open Graph tags for your front page than a single article. If you’re calling different header.php files for your front page and your single articles then there’s no problem, but if you’re using the same header.php you’ll need some sort of conditional statement that will load different Open Graph tags.

That might look something like this:

<?php
	// Show Facebook OpenGraph tags based on what page is displayed
if ( is_home() ) {
	//show OG tags with static info on front page, og:type  'website'
    include('og-frontpage.php');
} else {
	//show OG tags with dynamic info for articles, og:type  'article'
    include('og-single.php');
}
?>

The WordPress built in function is_home() will return TRUE when displaying the front page and the function will load og-frontpage.php with your Open Graph tags for the front page (with og:type of blog) or, for your single pages it will load the og-single.php

You’ll be able to use built in WordPress functions like the_permalink() and wp_title() to dynamically insert meta data about the single page being displayed.

There ya go, a simple way to dynamically change which Open Graph meta data you pass along based on the type of page being displayed.

TO TOP Subscribe RSS Twitter!