JavaScript in PHP

Lately I’ve been seeing a few themes that like to include and devote an entire file to JavaScript. There is a reason I don’t like this. Biggest one is because it creates bad practices. Yes, I understand you want to pass some variables between the two languages but there are better ways. What’s super cool is that WordPress has this amazing function that theme, and plugin, developers can use.

Enter: wp_localize_script

It’s a great and amazing function. So the question is, when should it be used? A great example would be ( dare I say ) a slider. Yes, I know. The dreaded sliders. People love them but often have to make changes to files that could be lost when the theme updates.

Recently I was fiddling around with bxslider for fun. Neat little library and fun to use when you get the hang of it too. Really customizable with several options.

So, on to the code portion!

The first thing we do is to create our settings. I highly encourage the use of the customizer when possible so we will use it as our starting point. In this example, we create a setting for the slider’s autoplay setting. A simple setting that the user can turn on or off. The slider does have many more options that you can configure but we will stick to simplicity for this example.

$wp_customize->add_section( 'demo-slider', array(
	'title' => __( 'Slider options', 'dademo' ),
	'description' => __( 'Set the slider\'s options', 'dademo' ),
	'priority' => 130
	) );
$wp_customize->add_setting( 'demo-slider-auto', array(
	'default' => false,
	'sanitize_callback' => 'demo_checkbox'
	) );
$wp_customize->add_control( 'demo-slider-auto-setting', array(
	'label' => __( 'Autoplay', 'dademo' ),
	'section' => 'demo-slider',
	'settings' => 'demo-slider-auto',
	'type' => 'checkbox'
	) );

Please note, I have not included the demo_checkbox function. That is a simple function that checks for true or false which you can add yourself. From there we enqueue our scripts and possible styles if you are using or wanting any.

wp_enqueue_script( 'slider-js', get_template_directory_uri() . '/js/jquery.bxslider.min.js', array( 'jquery' ), null );
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/jquery.bxslider.css', null );
wp_enqueue_script( 'demo-js', get_template_directory_uri() . '/js/demo.js', array( 'slider-js','jquery' ), null );

Now, the only thing that is missing is to use wp_localize_script to create our JavaScript object. Yes, you read that right: JavaScript object.

In order to do that we first have to look at the function itself and see how it works. So let’s break it down a little, shall we?

Parameter, the first

The first parameter that we pass to it is the JavaScript file that we want to localize. The key thing to remember is that the script has to be already registered or enqueued, otherwise it will not create the object. For our example, we would use it after our slider is enqueued:

wp_enqueue_script( 'slider-js', get_template_directory_uri() . '/js/jquery.bxslider.min.js', array( 'jquery' ), null );
wp_enqueue_script( 'demo-js', get_template_directory_uri() . '/js/demo.js', array( 'slider-js','jquery' ), null );
wp_localize_script( 'slider-js', 'demoObj', $jsObj );

Our new object

Second, is the name of the JavaScript object that is created and used in our external JavaScript file or files. In this case it would be the demo-js file. Behind the scenes the function creates the variable and uses wp_json_encode to create our object. For this example the newly created object is called demoObj. It can be anything you want but ideally you want to prefix it so it won’t interfere with any other objects or even plugins. Yes, plugins.

Our user settings

Finally, we pass an associative array to the function. This is where your user settings will reside. In this example you can see we create a simple property of auto for our newly created JavaScript object. We then pass the array to wp_localize_script so it can be output in our header’s <head> element and used in our JavaScript files.

$slider = array();
$slider['auto'] = get_theme_mod( 'demo-slider-auto', false );
$jsObj = apply_filters( 'demo_slider', $slider);

wp_localize_script( 'slider-js', 'demoObj', $jsObj );

Yes, I like using filters when possible that way a child theme can override it. You don’t have to do it but it is something to think about. As I mentioned, behind the scenes, wp_localize_script will create the JavaSCript object and output it in the <head> section. The <head> output will look a little like the following snippet.

<script type='text/javascript'>
/* <![CDATA[ */
var demoObj = {"auto":""};
/* ]]> */
</script>

As you can see it creates a global variable that can be used in any JavaScript file. Since it is a simple example it created only one JavaScript property for the demoObj object.

What next?

Great! We have our newly created JavaScript object but how do we use it? What’s super neat is we can use it like any other JavaScript object when we get a property.

jQuery( document ).ready( function( $ ){
	$( '.gallery' ).bxSlider( {
		'auto': demoObj.auto,
		// alternatively use bracket notation
		// 'auto': demoObj['auto'],
	});
})

That’s great for settings, what happens when you are dealing with interaction or even text? A simple example would be adding a small dialogue when a user adds an item to a shopping cart. With wp_localize_script you can do it. Pippin has great example of this in his article.

So go explore and break things!

Displaying multiple pages on one

Every so often I come across a theme or an implementation I like and wonder how it is being done. I like to dig behind the scenes on themes and see how they do things. Taking things apart to see how they work is a great way to learn.

One neat little tidbit I learned was how to create a page template that can use content from other pages and append it.

The steps

  1. Write code
  2. ???
  3. Have a celebratory drink

Step 1: Write Code

Yes, we will be writing quite a bit of it. Okay just enough to get the ball rolling and demonstrate the concept. One of the first things we need to do is figure out how many pages we want to show on our page template. I’ll use a smaller number like one to get started. You can add more if you want but because this is for demonstrational purposes we’ll keep it nice and simple.

So first, we will create our setting in the customizer:

$wp_customize->add_section( 'my_theme_page_sections', array(
	'title'    => __( 'The first page', 'text-domain' ),
	'priority' => 130,
) );
$wp_customize->add_setting( 'my_theme_page_1', array(
	'default'           => '',
	'sanitize_callback' => 'my_theme_sanitize_dropdown_pages',
) );
$wp_customize->add_control( 'my_theme_page_1', array(
	'label'             => __( 'Page 1 content', 'text-domain' ),
	'section'           => 'my_theme_page_sections',
	'priority'          => 30,
	'type'              => 'dropdown-pages',
) );
// the sanitize callback
function my_theme_sanitize_dropdown_pages( $input ) {
	if ( is_numeric( $input ) ) {
		return intval( $input );
	}
}

Next, we can create our actual page template.

/**
 * Template Name: Multiple pages
 *
 */
get_header(); 
	while( have_posts() ) : the_post(); // beginning of the loop
		// The page content of the selected page.
		// something basic can work like 
		the_content();
		wp_link_pages();
	endwhile; // end of the loop
	// Here is where the fun part is!
	rewind_posts();
	my_theme_selected_pages();
get_footer();

Yes, I’ve left out a lot of the markup but that’s only because the styling will be different for everyone. As you can see the part that creates the extra content is the function my_theme_selected_pages. That means we have to create this function somewhere. It can look something like:

$page_1 = intval( get_theme_mod( 'my_theme_page_1', '0' ) );

if ( 0 == $page_1 ){
	return;
}

for ( $number = 1; $number <= 2; $number++ ):
	if ( 0 != ${'page_' . $number} ) :
		$selected = new WP_Query( array( 'page_id' => ${'page_' . $number ) );
		// Our newly created loop with our selected page(s)
		while( $selected->have_posts() ): $selected->the_post();
			the_content();
			wp_link_pages();
		endwhile;
		wp_reset_postdata();
	endif;
endfor;

As you can see I have made it super simplistic. You can add more pages if you want. The key is making sure that $number<=2 matches the right amount of pages you want to add. So if you wanted to add five you would change the 2 to a 5. Yes, I left it at two because I forgot to change it.

Step 3: Celebrate!

Okay, maybe style it up if you want but I’m going to celebrate with some coke zero.

My gripe with widgets

Yes, I don’t like widgets. Okay that is not entirely true because I am using a few but it’s not what I’m referring to. What I’m referring to is when themes include widgets.

Themes that include widgets for contact forms, testimonials, group -or team- members of a company. Dare I say it? Newsletter widget. Cue dramatic music. Yes, I am referring to most of those. The reason I hate them is because you lose it once you switch a theme. It reminds me of the shortcut icons I see being used by a lot as well. It does drive me up a wall.

Up a wall, you say?

Yes. The reason for that is because there are dozens, and dozens of plugins that can do it and possibly do it better. Some things are not meant to change. The shortcut icon ( favicon ) should be one. In my opinion some widgets should be the same way. I make an exception only because I know there is at least one theme that unregisters core widgets and includes their own extended version of that widget. You still lose that functionality ( keyword right there ) once you make a switch to a new theme.

I know you may be asking and even wondering what argument, or arguments, could be made. Well, some people never change their themes. True. The thing to remember too is that even down the road they may just think about changing that theme. It will be a bad experience once they change that theme and lose the widget(s) they had.

There are some that are purely aesthetic and add to the theme’s experience but should that be the end all to turn to for widget design, functionality? I don’t know but it does seem a little strange that I haven’t seen many themes proclaiming support for certain widgets.

Start a trend

Yes, it would be nice. At least to see some theme authors supporting more and more plugins or specialized widgets. I mean after all that is what the description is for or even the theme’s documentation, right?

Why a theme’s changelog is important

Having some history is a good thing and knowing what changes were made and why is even better. That is one of the reasons that I love seeing a changelog when I look in a theme’s folder. Supposing they have one.

Not all themes are created equal

It’s true. When I speak of themes I generally refer to the themes submitted and maintained in the WordPress.org repository. I don’t mean those that you buy either. I don’t like to because I feel you pay for a certain level of not just support but dare I say care? I don’t know. Just two slightly different areas to me.

The reason I bring this up is because in the middle of making a change to my current project at hand I wanted to know why I chose to use a specific method and why it wasn’t working. At least on my working copy of the project. I tried to think back on what changes I had made and realized I hadn’t kept track of any changes; let alone major ones.

It reminds me a bit of history class. Military History to be exact. Yes, I took that class in high school. It was fun and a neat class to take. I learned a bit about why you use certain strategies and when. Kind of see where I’m getting at? Tactics, planning and thinking ahead were all at play. I just didn’t really think about it at the time. That and documentation. I didn’t do that part.

A little flashback

Over a year ago I came across two trac tickets. #45 on the WordPress meta side and #22810 on the core side. The downside is that is hasn’t had a lot of attention. ( That needs to change ). Personally I think it is a step in the right direction for themes. Users, end-users and developers alike. The reason is of course to keep track of what changes were being made and why. A good thing to look at and know so things won’t break and if they do you’ll have an idea of why and what to look for.

A good example is WordPress core itself. If you checkout the timeline it shows you what changes ( if you look at the changesets ) are made to the project itself. It’s a great reference point to keep if something breaks down the road. One reason I’ve liked using some form of version control is because of that.

Many themes I’ve come across could benefit from this because they make a lot of changes.

A long road ahead

Yes, there is a lot to be done when it comes to themes and better practices. I think a changelog is good one to have. It’s a lot easier when you are using a version control system. Just append the commit message to the file and you have your changelog. Do keep in mind that is one way of doing it, there are others.

I think this may be the bigger hurdle to get over. The formatting of said changelog. I’ve seen more and more that link to a github repository of all the commits, which can be good if you have an internet connection and a reliable one at that.

If you feel like that changelog needs to happen then please go and comment on the tickets. Create a patch. Do something about it.

Making a Portable Object Template for your WordPress theme or plugin

Yes, a bit of a lengthy title but I feel will get the point across and it is after all what I’m wanting to share with you today.

A what now?

A .pot ( or a Portable Object Template ) file is what WordPress uses and many PHP programs use for translation purposes. There are three files used. According to icanlocalize.com the files are:

  • MO – Machine Object. The MO file includes the same contents as PO file. The two files differ in their format. While a PO file is a text file and is easy for humans to read, MO files compiled and are easy for computers to read. Your web server will use the MO file to display the translations.
  • PO – Portable Object. This is the file that you receive back from the translators. It’s a text file that includes the original texts and the translations.
  • POT – Portable Object Template. This is the file that you get when you extract texts from the application. Normally, you send this file to your translators.

The one we will worry about is the last one. The POT file. There are several ways to create this file but the one I’ve found most useful was the one Otto was awesome enough to post for theme reviewers. It is super simple and does need a little tinkering and getting over the fear of the command line.

Yes, the command line. You know that little program that uses only text. No, not a text editor. Would be cool but no. Depending on the platform you are using it will be called a terminal window, command prompt or even powershell. All of these will work for what we will be creating.

Steps and requirements

Sorry, did I not mention there would be some requirements? The basic requirement is the command line and having PHP installed. The next would be getting the needed files from the repository. If you aren’t developing themes using a development version of WordPress leave your address in the comments below, I will find you and I will hit you. Hard. Even a release candidate is worth your investment unless you like to break things and have people yelling at you.

The tools and files you will need are in one of two locations. The first being in the svn developer site. You will need some sort of SVN software in order to get it, of course. The other would be from my github repo I created and modified. Yes, I created it just for this reason.

So the steps are as follows:

  1. Get files
  2. Extract files to correct folder
  3. Open command line
  4. Do some magic – or Voodoo, your choice
  5. Do happy dance!

Getting the correct files

I mentioned and linked two places where to get the needed files. The github link is the one I will go over. Part of that reason is not everybody will be fully familiar with version control or comfortable enough to not break things. Once that is downloaded we can open the zipped folder and move on to the next step!

Extracting the files

This is super simple thing to do. Extract the files to the root of your WordPress folder. It should look something like the image.

WordPress folder
WordPress folder

Open the command line

Now, there are several tools that are available for this. For Windows user there are two that I will often switch between: command prompt and powershell. I like using powershell more. We then will change to the directory where we have our WordPress installation.

For the next step will be going over some code, so be prepared.

Doing the magic

So here is where the real magic will happen. Once we are in the folder of our installation we will once more change directories to the i18n folder where all translation files reside. From there we will run a quick line of code that will create our new POT file.

$ php makepot.php wp-theme /path/to/theme /path/to/languages/theme-slug.pot

The thing to keep in mind is the $ is just a placeholder for the current directory you are in. It may differ from machine to machine. Once we have run that it will create a new file ( theme-slug.pot ) with all translation-ready strings. So try not to forget to translate all text strings!

How it works

I know there are a few people wondering how this actually works. I know I was for bit. I’ll try my best to make it a little more understandable why you need to have certain things in your command line.

The first thing you need to know is what you are doing. When you state php you are to a degree saying, “I want to run PHP code and use this file.” The next three things are what you are going to pass that file.

  1. The first thing we passed is what type of project you are creating the pot file for. In our case it is a wp-theme. There are a few other you can decide from like wp-plugin, wp-admin, wp-core and a few more that I just won’t list.
  2. The second thing we passed is the location of where to look for the translation functions. If you read through the list of what functions it looks for you are in for a treat because that list you can add to Poedit. (I’ve slowly walked away from that but would still recommend for beginners.)
  3. The last thing is the output of the file. Both the location and the name ( be sure to include the extension as well ) are what we will be using.

Now, you can do this with your plugins as well. Just be sure that the folder you are creating the POT file to does exist otherwise you will get errors and it won’t create the file for you.

I stated earlier that it works with a few changes; it’s true. The reason being I know there are some people who don’t like to use a development version of WordPress. Why? I don’t know but I made a few tweaks for it to work the way it works. Okay, I only changed three things but it works for the time being. I say that only because I’ve tested it on/off since the original post. If you encounter any issues please be sure to let me know!

Celebration will begin

There we have a newly created POT file ready to be sent to a translator. So, yes, by all means do your happy dance. Not only did you get over the slight fear of the command line but you possibly learned something new along the way.

Notes

If you don’t specify a path of where your theme/plugin resides it will create an error and will not work!
If you don’t specify a path, just a name for the file it will create the file in the i18n folder.

Making a few commits

Let me give you a little bit of a back story first.

2 years ago

I began posting on the WordPress.org forums to help people out. I would only post on things that I knew for sure I knew the answers to or would help out. It felt like it at the time. Who knows really. It was, after all, two years ago. Not only that I would only really post at most twice a week. It was fine only because I didn’t have a goal in mind.

Yes and no. I had a goal in mind: to help; to share my knowledge. A lot has changed since then of course. Now, I have a slightly different goal in mind: make a career out of helping people. Yes, it may sound a little cheesy but it is true. A lot of it does stem from working at Starbucks. Many of the ‘regulars’ know that I won’t lie to them and will try my hardest to find something they will like. Now, I’m getting a little sidetracked.

Push forward

Over those last two years I kept mentioning a theme I was working on. Funny thing is I did and I didn’t. Part of that reason was I kept putting it aside. I would do a theme review, post a solution to the forums or see how I could help out somebody in the IRC channels. You know what? I loved every encounter and every sentence I wrote and read. So really it’s hard to be upset. I learned a lot from it all. Not just WordPress but programming in general.

Yes, I did also pick up a few other things along the way like the basics of SVN and Git and how to create a simple repository with those tools.

It’s safe to say the last two years I have been fairly busy. I have reviewed more themes, posted more often on the forums, make an attempt to post on IRC more frequently and have the honor of being one of  the Theme Review Team reps. It’s been an awesome year for me so far.

Say what?

Up until recently I never really said much about my theme. Yeah, I posted one or two photos of what it might look like but never any code. Okay maybe some code but never really said it was.

I began my theme with one thing in mind: simplicity. It sounds overly repetitive since a lot of themes claim the same thing. You know what? That’s fine. Over time I realized one thing: I don’t want complete simplicity. It would be nice to have but I don’t think I would achieve it without deleting the entire project. I mean how much simpler can you get with no code?

So, here goes, what I have been working on/off for the last year or so: Solea

Yeah, it’s not finished. There are a few things missing here and there but you know what? It can be expanded upon.

Child theme friendly post-formats

It’s no surprise I will always preach the making of child themes. Part of the reason is because you can make modifications without losing all that when it comes time to update the parent theme. I mean nothing more exciting than having to recall what files you changed, what code you added, deleted to brighten your day. Troubleshooting. It’s amazing.

The dilemma

Currently the biggest issue I’ve really seen is post formats. It’s not really easy to add to the parent theme. I mean yes and no. Adding to the list is not entirely possible without some parent theme editing and that is what I actually did. I created a quick function that checks and adds to the list of post formats.

The code

function get_theme_post_formats(){
    // $core_formats = array( 'link', 'chat', 'quote', 'gallery', 'status', 'image', 'aside', 'audio', 'video' );
    // base support for the theme
    $formats = array();
    // child if it wants to add
    $child_formats = apply_filters( 'theme_post_formats', array() );
    foreach( $child_formats as $key => $format ){
        if( ! array_key_exists( $format, $formats ) ){
            $formats["$key"] = $format;
        }
    }
    return $formats;
}
add_theme_support( 'post-formats', get_theme_post_formats() );

How it actually works is pretty nifty. What those fourteen little lines of code does is create a filter for child themes to use. That filter is: theme_post_formats. What you would do in the child theme’s function file is something like:

add_filter( 'theme_post_formats', 'child_formats' );
function child_formats(){
    return array( 'link', 'status', 'gallery' );
}

What that will do is add to the list of post formats of the parent theme. The way WordPress core makes you do it is by re-declaring the formats. What I mean by that is you have to call the function add_theme_support and list the already supported formats and add. Seems like a little too much work for some. At least how I feel about it; some may or may not agree with that.

To show you what I mean:

// Parent theme declaration
add_theme_support( 'post-formats', array( 'link', 'gallery', 'quote' );

// Child theme declaration
add_theme_support( 'post-formats', array( 'link', 'gallery', 'quote', 'status', 'chat' );

As you can see both can work. What it boils down to is how you want people to extend to your theme.

Getting the image count in WordPress

A long time ago I had a bit of an issue on how to get the image count from a post. At the time there wasn’t a way that I could think of to properly getting all the needed information; but then again I didn’t know as much as I do now.

I wanted to revisit this because I know it will help out at least one person if not more.

Since the last time I brought up the topic of multiple galleries in one post a lot has changed and a few new functions were added to help solve the dilemma. The key one that helped is: get_post_galleries

It was a simple idea but for some reason at the time it kept only giving my brain a beating. The reason was because it wouldn’t give the correct image count.

New solution

Up until now I was a little confused how I would solve my issue. I knew I needed to get all the galleries and then I needed to get all the images in those galleries. So, here is what I did:

// Get all the galleries in the current post
$galleries = get_post_galleries( get_the_ID(), false );
// Count all the galleries
$total_gal = count( $galleries );
/**
 * count all the images
 * @param array $array The array needed
 * @return int returns the number of images in the post
 */
function _get_total_images( $array ){
    $key = 0;
    $src = 0;
    while ( $key < count( $array ) ){
        $src += count( $array[$key]['src'] );
        $key++;
    }
    return intval( $src );
}

echo _get_total_images( $galleries );

As you can see it really isn’t much code. Part of that reason I wanted to keep the code as simple as possible. Feel free to extend it. In fact, I encourage you to do it.

How it works

What’s nice about the way I went about it is that it will require at least WordPress 3.6 and higher or else you will get an error. Nobody wants those, right?

The first thing we did was create a holder for all the galleries with the get_post_galleries function. We then count how many galleries there are and store that in another variable. That way we can use that later on to output the number if we want. Some people like that sort of thing.

Line 10 is where it goes a little different. I know you’re wondering why I’m declaring a function and then echoing that function in the last line. Part of that reason is because I wanted the ability for child themes to easily filter the text that I would use. Yes, I am aware I didn’t include any text strings. I’m pretty sure you can guess what it would say though, right?

Now, with that little tidbit in your arsenal go and read some code from the includes folder. You won’t be let down.

You don’t know text

Okay, maybe you do but what I’m talking about is a different kind of text. I’m talking about text strings in PHP code.

Text strings

What are they? Why do they matter? Well, they matter in themes that you want to make public or share. Oh, and plugins as well, I guess. If you’re into that sort of thing.

Over the last few weeks I’ve come across a few themes that didn’t quite make every line of text translatable. It almost drove me mad. Seriously. I was about ready to just punch my monitor. Thankfully another song came on and I was back to my calm self.

Functions

Yep, they do exists within WordPress. It’s actually quite nice that they do. Here are some that can be found in the includes folder:

  • __( 'I am a text string', 'theme-domain' )
  • _e( 'I am echoed', 'theme-domain' )
  • _x( 'Form', 'Art related', 'theme-domain' )
  • _ex( 'Form', 'Filing related', 'theme-domain' )
  • _n( 'Single', 'Plural', 'Number', 'theme-domain' )
  • _nx( 'Single', 'Double', 'Number', 'theme-domain' )
  • esc_attr__( 'I am an attribute', 'theme-domain' )
  • esc_attr_e( 'I will be an echoed attribute', 'theme-domain' )
  • esc_attr_x( 'Link', 'hyperlink', 'theme-domain' )

There are a few more but those are some of the ones I feel would be used more often than the others. In particular the first two. Those are by far the easiest ones to really miss. At least those are the ones I seem to find not being used when they should be.

What qualifies as a string?

When it comes down to it: anything that is inside markup. If it is wrapped inside an HTML tag then odds are it is a text string. A great example of this would be a very common line used by many themes. The “posted on” phrase. Now, there are several ways of doing this but I feel there are very few that are correct when it comes to translation strings.

$phrase = 'Posted on %s by %s';
printf( $phrase, get_the_time( get_option( 'date_format' ) ), get_the_author();

As you can see from the example I’ve provided it is a simple phrase that can easily be translated. The only thing you really have to do now is wrap the actual phrase with a translation function like:

$phrase = __( 'Posted on %1$s by %2$s', 'text-domain' );
printf( $phrase, get_the_time( get_option( 'date_format' ) ), get_the_author();

Fairly simple, right? But what about when it comes to numbers? That is what _n() is for actually. It’s a neat little function to use. It compares numbers! Yes, numbers. I love those things.

Okay, not literally compare numbers but fairly close. What it does do is actually determine which version of string to use. Sort of a juggling function with a twist. Really cool to use when you want to compare a single use, plural or even more.

A good example would be using it in a shopping cart.

echo "<h4>Items in cart</h4>";

$count = _n( 'Only one so far', 'Two items', get_total_items(), 'text-domain' );
printf( '<div class="cart-total">Currently: %s</div>', $count );

Pretty neat, right? I think so.

There are a few more functions to make translating a theme, or plugin, better but I feel those are the ones I find a bit more useful.

A whole new widget experience

If you haven’t already then go check out and read the proposal made by Weston. When I first saw this I nearly peed my pants from joy. It was that amazing. Being able to see the widgets live is going to be a huge thing. Not just for theme developers but for plugin developers as well.

One of the things I’m really looking forward to is being able to see how any widget will look like rather than having to have a separate tab open and then refreshing it. Yeah. That’s how preview widgets. That was until I came across the plugin. See it in action:

http://youtu.be/D1GHc5OGWEQ

Now, as you can see at the moment it does have a few things that may need a little polishing but that’s okay.

Now, the one thing to keep in mind is that you may have to add a line of PHP in your theme’s functions file. Easy really. Just one:

add_theme_support( 'widget-customizer' );

And boom! Now your theme is able to create live widget previews.