Widgets and when to use them

Widgets are a great way of showing information in specified areas. Themes handle this in different locations and different ways. Some have page template with up to thirty widget areas. Yes, thirty! Sorry, felt like a salesman when I typed it out but it is true. And then you get the occasional theme that wants you to type out content. Yes. Dealing with themes and content.

The reason I’m not a fan of this is because once the theme is switched you lose that content. I know some will ask how much content is too much content? Any content that isn’t theme specific is too much.

What drives me up a wall more is when some themes bundle a widget that core is more than capable of handling. A very common one is the infamous call to action button widget. Yes. I dislike that button widget. You can use core’s text widget! Let’s see an example shall we?

$text = sprintf( __( "You can use <small>%s</small> as well as basic HTML.\n\n You just <strong>cannot</strong> use JavaScript.\n\nThis is a <em>sample</em> with auto paragraphs being used.\n\nWhat next?", 'text-domain' ), allowed_tags() );
the_widget( 'WP_Widget_Text', 
	array( 
		'title' => __( 'Using a text widget', 'text-domain' ), 
		'text' => $text,
		'filter' => true
		),
	array(
	  	'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	  ) );

Yes, it does look like quite a bit of code but there is a reason for it. The function that does the magic for us is the_widget. What’s super cool is that this means you can create an instance of a widget to create a great looking theme preview. Not only that it can serve as a bit of documentation for your theme.

Let’s take a look at another example, shall we?

The plugin I used is Feature a Page. All I did was a simple search in the plugin repository and picked one at random.

if ( class_exists( 'FPW_Widget' ) ):
the_widget( 'FPW_Widget',
        array(
            'title' => 'About our Clients',
            'featured_page_id' => '1141', // ID of page
            'layout' => 'banner',
            'show_title' => false,
            'show_image' => true,
            'show_excerpt' => true
        ),
        array(
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget'  => '</aside>',
            'before_title'  => '<h3 class="widget-title">',
            'after_title'   => '</h3>',
          ) );
endif;

Let’s run through the code a little. The first line checks to see if the class FPW_Widget exists. If it does, then we can run our code. As you can see the second argument we’re passing is an associative array with some settings we want our widget to display.

In this particular case the widget has some settings that we can change. They are:

$defaults = array(
	'title' => '',
	'featured_page_id' => '',
	'layout' => 'wrapped',
	'show_title' => true,
	'show_image' => true,
	'show_excerpt' => true,
	'show_read_more' => false
);

They will vary from widget to widget so be mindful of that. The codex page has the default widgets and their respective settings that you can change.

Now, what’s neat is that you can use the third argument in order to style the output of the widget. To a degree. Let’s look at the first example:

array(
	'before_widget' => '<aside id="%1$s" class="widget %2$s">',
	'after_widget'  => '</aside>',
	'before_title'  => '<h3 class="widget-title">',
	'after_title'   => '</h3>',
) );

Notice that I’m using a simple copy paste of what a register_sidebar call would do. In particular the before|after_widget, before|after_title parts. Reason being, odds are, you’ve styled the widget areas with certain CSS classes and using those instead of the default ones the_widget uses. Core markup is:

$before_widget = sprintf('<div class="widget %s">', $widget_obj->widget_options['classname'] );
$default_args = array( 'before_widget' => $before_widget, 'after_widget' => "</div>", 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>' );

So if you don’t define the third argument, what will be used on output is the above.

Additional notes

I used the plugin because it is a great example of how you can pull user generated content to create a widget. What’s really nice is there are several plugins that create widgets and deal with widgets. Don’t forget that you can even use a simple setting in order to create a featured content area as well. There are several themes that do this already so explore their code and learn from them.

Working with the WordPress Customizer

Recently the Theme Review Team chose to make the customizer as the format of creating theme options. I love it! Yes, I was in favor of it. I have my reasons. I know there are some people that still don’t fully grasp the customizer and most likely won’t. All good! Some take a little more time than others; I know I do sometimes with certain things.

How it works

Okay. This little post will deal with customizer settings, controls, sections and panels. Yes. At the time of this writing the WordPress version is 4.2.1 with 4.3 just beginning. In the following I will make an attempt at giving you ( the reader ) a little more insight into how the WordPress customizer works and what is available within the customizer.

In order to understand the customizer a little more I dove into the core code. I asked myself a simple question, “when and where is it being created?”

Funnily enough it is done in one simple function. _wp_customize_include. It is a callback function that is hooked to plugins_loaded. Yes, I went ahead and looked up a lot of the code for you. What’s pretty cool is that in order for the customizer to work it needs five files. Yes, five. To a degree 7 but the other two are the customize.php and class-wp-customize-widgets.php files. For the purpose of this post I’ll only really dive into the five customizer ones.

Let’s look at the function:

function _wp_customize_include() {
	if ( ! ( ( isset( $_REQUEST['wp_customize'] ) && 'on' == $_REQUEST['wp_customize'] )
		|| ( is_admin() && 'customize.php' == basename( $_SERVER['PHP_SELF'] ) )
	) )
		return;

	require( ABSPATH . WPINC . '/class-wp-customize-manager.php' );
	// Init Customize class
	$GLOBALS['wp_customize'] = new WP_Customize_Manager;
}

The key thing to remember is when you are creating your options, you are passing an object. The $wp_customize global object to be a little more specific. As you can tell from the function above, you are creating an instance of the WP_Customize_Manager and setting that as the $wp_customize global variable that can be accessed by using:

global $wp_customize;

Looking at the __construct method, it loads the needed files and adds a few filters and hooks in order for the magic to happen. Totally awesomesauce!

Boom! We have our customizer! Great! But how do we add stuff?

Adding things

In order to add our theme options we have to hook to the right place. The codex has a great explanation on this, though currently it is missing a section on how to add panels. Yes, you can add panels in order to make your theme option logic make some sense for a user.

So, in order to add things we need to know how, right? Right! What’s pretty neat is that the customizer does this with built in methods. Yes, it is very object oriented. One of the other reasons I like it. There are four methods that will help in creating a great customizer experience.

$wp_customize->add_setting();
$wp_customize->add_control();
$wp_customize->add_section();
$wp_customize->add_panel();

I say customizer experience because as a developer you will have to think about the logic of your theme options. That’s great and all but what actually starts it all? The part that we hook to in order to start our theme options is the customize_register hook. This is done from within your theme by using:

add_action( 'customize_register', 'my_theme_customize_regiter' );
function my_theme_customize_register( $wp_customize ){
	// Theme settings/options code goes here
}
// or if using a class
add_action( 'customize_register', array( 'My_Class_customize_register', 'register' ) );
class My_Class_customize_register {
	public function register(){
		// Theme settings/options code goes here
	}
}

Got it? Cool! Let’s keep moving! Let’s break down each method a little more.

The methods

What’s super cool is that the customizer makes it super easy to create a theme option experience. It does this with four different methods. Let’s take a look at each one and what each one has to offer.

add_setting

The first one we will look at is the settings. In order to create a theme option in the customizer we use the $wp_customize->add_setting method. It takes two arguments. The first one is the ID of the setting and the second is an associative array. It looks a little like:

$wp_customize->add_setting( 'theme_option', array(
	'default' => '', // The default setting
	'type' => '', // can use 'theme_mod' or 'option'
	'capability' => '', // generally 'edit_theme_options'
	'transport' => '', // can use 'refresh' or 'postMessage'
	'theme_supports' => '', // internally used in customizer
	'sanitize_callback', // the callback before setting is saved to database
	'sanitize_js_callback' => '' // used for the JS value
	) );

You don’t have to use all of them. The ones that matter most are the default, option, transport, and sanitize_callback arguments. The reason option is one that matters is in the way it will save the options into the database. The sanitize_callback matters because it runs before the setting is saved to the database so you have to make sure to sanitize it. The transport value can be important if you want the page to do a full refresh or if it will be AJAXified.

add_control

The next one to look at is the $wp_customize->add_control. This is what the user will see. Much like the add_setting it, too, we have to pass two arguments. The first one being a unique ID, and the second being an associative array.

$wp_customize->add_control( 'option_control', array(
	'label => '', // label for the control
	'description' => '', // description of the control
	'settings' => '' // the setting 
	'section' => '', // core ones are: 'title_tagline', 'colors', 'header_image', 'background_image', 'nav', 'static_front_page'
	'type' => '', // core ones include: 'checkbox', 'radio', 'select', 'textarea', 'dropdown-pages', 'text'
	'choices' => array(), // associative array of 'value' => 'option user sees'
	'priority' => '', // the higher the number the lower it will appear from the top
	'input_attrs' => array(), // associative array of 'attr' => 'value'
	'active_callback' ='' // based on preview context
	) );

So, we have a few options with the controls. Cool, right? What’s even cooler is that there are few others to use. You can also use WP_Customize_Image_Control, WP_Customize_Upload_Control, WP_Customize_Color_Control, and WP_Customize_Media_Control. They just require a little extra code.

$wp_customize->add_control( new WP_Customize_Media_Control( $wp_customize, 'media_control', array(
	'label' => 'Image selection',
	'description' => 'Choose an image',
	'settings' => 'default_value',
	'section' => 'random_slider'
) ) );

add_section

Great! Now that we know how to create a setting and a control, we can look at how to create a section to hold those settings. You’ll notice I’m using settings and options a little interchangeably. As stated earlier you can choose how to save things to the database. The theme_mods or option. How you do it is up to you. Now, let’s look at how to create a section, shall we? This too, like the previous two takes two arguments. A unique ID and an associative array.

$wp_customize->add_section( 'my_section', array(
	'title' => '', // the title of the section
	'description' => '', // description of the section
	'priority' => '', // the higher the number the lower in the customizer from the top
	'capability' => '', // default setting is 'edit_theme_options'
	'panel' => '', // if none it will show on main panel
	'active_callback' => '' // based on preview context
	) );

Simple and fairly straight-forward, right? What’s pretty cool too is that you can use the active_callback to your advantage. For example if you wanted to show a certain section only a widgetized area was being used. You could use a callback like:

// in the customizer
'active_callback' => 'widgetized_cb'
// later on in the code
function widgetized_cb(){
	return is_active_sidebar( 'primary' );
}

add_panel

Pretty awesome right? See where some of that logic can come into play? Great! Now you know how to add settings, controls, and sections. We can finally take a look at the final one: panels!

What’s super awesome is that this, too, uses two arguments. A unique ID and an associative array. Notice a pattern here? Let’s look at the available ones:

$wp_customize->add_panel( 'my_panel', array(
	'title' => '', // the title for the panel
	'description' => '', // short description of the panel
	'priority' = '', // the higher number, the lower from the top
	'active_callback' => '' // based on preview context
	) );

As you can see not a lot for the panels – yet. The customizer is constantly being worked on in core. There are a lot of things you can do to make it better if you want to help out.

Previewing

Okay, this is the part where things really come together because it deals with JavaScript. You remember in the add_setting there was an option for transport? If you want to create live previews without the entire page being refreshed, you set it to postMessage. In order for it to take place you will have to include a little JavaScript. I would highly recommend using a dedicated file for this. All you have to do is hook to the right place and enqueue it.

add_action( 'customize_preview_init', 'my_theme_preview' );
function my_theme_preview(){
	wp_enqueue_script( 'my-theme-js-preview-file', get_template_directory_uri() . '/js/my.customize.preview.js', array( 'customize-preview' ), '', true );
}

From there your JavaScript file would include something like:

wp.customize( 'setting_id', function( value ) {
	value.bind( function( newvalue ) {
		// do things
	} );
} );

Final thoughts

So there you have a slight crash course on how the customizer works and what options are available to create a good theme option user experience. There are a few little tricks and things you can also do, so go ahead and explore the core code and find out! You’ll be amazed at what you will find.

Fun with template tags: comments_template

On my last post I talked about dynamic_sidebar and some uses. It was a fun little experiment I wanted to do and share. Yes, I said experiment. That is how I learn. I read, do and then share. I know I’m not the only one that does that.

This time I dabbled with comments_template(). Yes, another one of the more common template tags. I wanted to dissect the function and see what really makes it unique. Okay, not really, I more or less wanted to look at the code and see how it gets the template file.

Core code

The code itself is about 90 lines. That is including the inline documentation. Without the inline documentation it is about 60 lines. Good to know. It means we don’t have to guess what is going on a lot. So let’s dive in shall we?

Okay, let’s break the function down, shall we?

The arguments

The first argument that is passed is the $file location. The second is whether or not to separate the comments. Simple. But what does that mean and how can we change this?

One way, of course is by passing some arguments ourselves. Let’s say we wanted to separate the comments, we would use:

<?php comments_template( '', true ); ?>

Or if we had our comment template in another location we would use:

<?php comments_tempate( '/inc/comments.php' );

That’s great if your comment template resided in the inc folder and was named comments.php. But what happens if you don’t have a comments.php file anywhere in your theme’s folder? Well, the nice part is that WordPress does account for that. The downside is that it creates a deprecated_file call. Yes, an error. If you read the following doc-block you can see why.

/**
 * @package WordPress
 * @subpackage Theme_Compat
 * @deprecated 3.0
 *
 * This file is here for Backwards compatibility with old themes and will be removed in a future version
 *
 */

I’m going to emphasize the part that really matters most:

and will be removed in a future version

Backwards compatibility is one thing that WordPress does really well; though this is one time I wish it would do it faster. At least for these files. There are a few other files but I’ll focus on this for now.

But why does it load that file if there is no comments.php file? Let’s look a little closer at what the function actually does. At least the parts that really make it load the needed file.

if ( empty($file) )
	$file = '/comments.php';

$theme_template = STYLESHEETPATH . $file;

$include = apply_filters( 'comments_template', $theme_template );
if ( file_exists( $include ) )
	require( $include );
elseif ( file_exists( TEMPLATEPATH . $file ) )
	require( TEMPLATEPATH . $file );
else // Backward compat code will be removed in a future release
	require( ABSPATH . WPINC . '/theme-compat/comments.php');

Not really much code, right? First it checks if the passed argument $file is empty and if it is it creates a simple string of '/comments.php'. Then, it creates a variable $theme_template with the constant TEMPLATEPATH and $file appended to it. Next we see a fairly familiar function apply_filters(). The filter name is comments_template.

We can then use a filter hook to change the location of our comments template. Granted we can do the same without even using the filter by simply passing it the location string to the function itself as we saw above, right?

It matters

Why am I bringing this up? I am bringing this up because the comments template file should be the place to be using wp_list_comments() as well as comment_form(). It doesn’t have to be comments.php that houses those template tags. It could be named anything you want, you just have to make sure you are loading the file properly.

Using a filter

One way is using a filter hook. As you noticed above the line:

$include = apply_filters( 'comments_template', $theme_template );

This what we can use. The code would look a little something like:

add_filter( 'comments_template', 'demo_path_to_comments_template' );
function demo_path_to_comments_template( ){
	if ( is_child_theme() && file_exists( get_stylesheet_directory() . '/inc/coms.php' ) ){
		return get_stylesheet_directory() . '/inc/coms.php';
	} else {
		return get_template_directory() . '/inc/coms.php';
	}	
}

Yes, quite a bit just for comments, right?

Using an argument

What’s super cool about using the core template tag and passing it the argument is that it will first look in the child theme ( if active ) and then the parent theme for the file you designate.

<?php comments_template( '/comments/pings.php', true ); ?>

In the above example it will first look for the pings.php file of the child theme ( if it is active ) and if that file does not exist it will load the parent file. Sort of what get_template_part() does. That is another neat little function for another post.

Seriously, it matters

I’m going to repeat this part because it bears repeating. The backwards compatibility file will one day be removed. Your users will thank you for not using the fallback file. It shouldn’t be a safety net for the theme. Besides, if you want the theme to be hosted in the repository it can’t have any errors.

Fun with template tags: dynamic_sidebar

The last couple of weeks I’ve been reading the core code more and more. I like it. Came to the conclusion I really don’t know every hook or filter. I don’t claim to though. I like knowing enough to make a functional theme or even a plugin. Yes, I’ve been recently dabbling with one but that’s for another post.

The reason for this post is to share some knowledge. Hopefully somebody finds this useful or helpful.

The function

For this post I will be using dynamic_sidebar(). It’s a fairly common template tag in themes. It gets a widgetized area and outputs them in a designated area. In order for that to happen you must first have a registered area. We do that by using register_sidebar(). For demonstrational purposes we will use:

register_sidebar( array(
	'name'          => __( 'Footer Area', 'dademo' ),
	'id'            => 'footer-area',
	'description'   => __( 'Add widgets here to appear in your sidebar.', 'dademo' ),
	'before_widget' => '<aside id="%1$s" class="widget %2$s">',
	'after_widget'  => '</aside>',
	'before_title'  => '<h2 class="widget-title">',
	'after_title'   => '</h2>',
) );

Great! So we created a widgetized area with an ID of footer-area. It can be anything we want but we will currently stick to simple naming conventions. Now, let us look at the core code, shall we?

The core code

The function itself is quite a few lines of code. Approximately 160 lines. I’m not going to post all of that code. The developer reference page has it and you can even view on trac. The ones that matter most for this post are two lines.

The first line:

do_action( 'dynamic_sidebar_before', $index, true );

The second line:

do_action( 'dynamic_sidebar_after', $index, true );

Notice something a little strange about it? I’m referring to the $index part of course. This is the neat part of it all. What does that little part mean?

Our hook

The cool part is that you can hook to specific widgetized areas if you want. I know you may be asking what I mean by this so I’ll demonstrate a little bit. Take our previous example of footer-area above and we will wrap it within a <section> element tag with a class of row.

add_action( 'dynamic_sidebar_before', 'demo_sidebar_before' );
function demo_sidebar_before( $index ){
	if ( $index == 'footer-area' ){
		echo '<section class="row">';
	}
}
add_action( 'dynamic_sidebar_after', 'demo_sidebar_after' );
function demo_sidebar_after( $index ){
	if ( $index == 'footer-area' ){
		echo '</section><!-- Widgetized footer area -->';
	}
}

From there it would render:

<section class="row">
	<aside id="recent-posts-4" class="widget widget_recent_entries">
	<h2 class="widget-title">Recent Posts</h2>
	<ul>
		<li>
		<a href="/2015/04/13/aesop-testing/">Aesop testing</a>
		/li>
		<li>
		<a href="/2015/04/13/sampling-some-code/">Sampling some code</a>
		</li>
		<li>
		<a href="/2015/04/08/another-gallery/">another gallery</a>
		</li>
		<li>
		<a href="/2015/04/08/gallery-7/">gallery 7</a>
		</li>
		<li>
		<a href="/2015/04/08/gallery-6/">gallery 6</a>
		</li>
	</ul>
	</aside>
</section><!-- Widgetized footer area -->

As you can see it created the section element and inside of it is a simple recent posts widget. Now, as I mentioned that is for specific widgetized areas. The thing to remember is to use the ID of the widgetized area to conditionally add or remove. It is that $index that is used to test. You can add things to every single dynamic_sidebar call by not even checking. Let’s say we have two widgetized areas. One in the footer and the other just above the content. We will call that section, “content-above.”

I know, very creative. I said it would be simplistic, didn’t I?

Okay, we wanted to add few things. Let’s say we wanted to add an image to both of those sections. We could edit two different files depending on how your theme is structured. Sounds a little painful, right? So, we will use our handy-dandy little hook:

add_action( 'dynamic_sidebar_before', 'demo_sidebar_before' );
function demo_sidebar_before( $index ){
	echo '<section class="row">';
	echo '<img src="' . get_template_directory_uri() . '/img/divider.png" />';
}
add_action( 'dynamic_sidebar_after', 'demo_sidebar_after' );
function demo_sidebar_after( $index ){
	echo '</section><!-- Widgetized area with image -->';
}

Pretty cool, right? What’s super cool is it will render like:

<section class="row">
<img src="path/to/img" />
<!-- widgets -->

</section><!-- Widgetized area with image -->
<section class="content row">
<!-- the_content -->
</section>

<section class="row">
<img src="path/to/img" />
<!-- widgets -->
</section><!-- Widgetized area with image -->

Yes, all that markup where ever you are using dynamic_sidebar().

Advanced fun

This part I’m writing as my left eye is twitching only because it deals with widgets in themes. Yes, I’ve never liked including them. This part deals with hooking to particular widgets in your theme.

Yes, you could simply edit the file that has the widget but where is the fun in that? This time we will use an action hook.

add_action( 'dynamic_sidebar', 'demo_sidebar' );
function demo_sidebar( $obj ){
	
	if ( $obj['callback'][0]->id_base == 'meta' ){
		printf( '<span>%s</span>', __( 'So much meta', 'dademo' ) );
	}
	// Alternatively
	// if ( preg_match( '/meta-/', $obj['id'] ) ){
	//	printf( '<span>%s</span>', __( 'So much meta', 'dademo' ) );
	// }
}

Does look a little complex, right? Let’s break it down a little.

First, we create the hook in line 1. Then we create our callback function in line 2. Doing good so far. Line 3 is where it does get a little odd. What does it mean? What does it mean?!

Okay, it may look a little complex to some but I’ll explain a little bit more.

When using dynamic_sidbar() it uses an array for the widgets. If there are no widgets then the function returns a false value. If there are it creates an associative array of the widget instance. That array is what we pass our callback function. In the example it is called $obj. In that array we have a key called callback. It, too, is an array.

We are looking for the first item on there because it holds the important part. The information about the widget object. The example is looking for the id_base of the widget. You know that little part you named when you registered the widget.

The alternative uses preg_match to match the ID of the widget’s instance. Yes, you can do specific instances as well.

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?

My 500 and counting

The beginning of the year I promised myself that I would try to review 500 themes by the end of the year. I finally managed to reach that point and was super ecstatic about it that I just had to tweet about it:

Yes, a tweet. Just one tweet. And I even went ahead and made another little challenge for myself for the next goal: 750. No timeframe for that just yet but I am happy I completed the 500 and am making some good traction for the next goal.

Since making that little challenge to myself a few things have changed. One of which is that I am now able to push themes live as well as others. Makes for reducing the queue a little easier and tolerable in my point of view. There are a few other things but I’ll leave that for another post and another time.

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.

Organizing all the media

Yeah, media. I love it. Most people live it and some are just indifferent about it. Blah! Is what I say to them. The reason I say it is because I love entertainment. Surprised? Don’t be. I am super easily amused. Like super easy. Like two-year-old easily.

A little history

The last couple of months I was trying to think of a way to organize my media library. No, not my computer. That would require way too much effort on my part and I just don’t have the attention span for it. I mean for my WordPress site. One thing that I felt could be improved. At least the experience.

My current library is the default one. Why? Because I never got a chance to get to it. I’ve wanted to change the layout for some time and use a grid system to display all the items. Do keep in mind I mostly have photos and very little audio and little-to-no video. For the time being. I will change that down the road, of course.

So here is the current look:

Media Library core

Recently I came across an amazing plugin that helped me do what I would like to do. At least for the time being. It’s called media grid. Simple solution that will hopefully make its way to core. As I write this out I’m also testing the development version and tweaking, trying to figure out how to break things and where it may break. It’s fun. You should try it one day. As Ferris Bueller once said:

“It is so choice; if you have the means, I highly recommend picking one up.”

Yes. I do believe in the plugin that much. Enough to write about it. Running through the paces I do have to say I love how it works on a desktop environment. The ability to change from thumbnail to a larger image is nice and being able to batch delete is great. Next phase – I feel – will be being able to preview the other media. Do remember that ever since WordPress 3.6 video and audio support were added and there are several plugins that also add other formats to the mix.

For me, the ones that matter most are video, audio, and of course images. So with the plugin enabled it does look like:

media-grid It is a little edited since the version I’m using wasn’t playing nice with the screen but that gives you an idea of what to expect. Pretty cool, right? So go, download it, try it out and if you’re feeling up to it: review it!

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.

Using a post as a menu item

Truly a neat little find for many people. I know when I saw this for the first I was beyond astounded.

It does seem a little odd to use one but there are some random cases when it can be useful. Rather than having to use a page you can use a post. Granted it will show up with all the other posts but it is a cool thing to know.

There are a few steps required:

  1. Create the post.
  2. Create a menu
  3. Create the menu item

The first thing is, of course, to create the post. Could be anything you want about whatever you want. A cat, a dog or even a random turtle you saw the other day.

Next, you want to create a menu. In order to do so you want to go to the Appearance section and select Menus. That will bring up the Menus screen. If you don’t already have a menu created, name it whatever you want and press the create button.

Finally, we create the menu item. This is where it can be a little tricky. Why, you ask? Well, by default WordPress shows three options. You can actually have more. You just have to look in the right place.

screen-options

When you click on the Screen Options tab you get a nice little selection of things that you can now edit. As you can see from the following image you now can choose tags, categories and even posts as menu items.

new-options
Options galore!

From there you will choose what you want. In our case we will check off all the options because we like to live dangerously and love options.

Now we see that have a few more things in our roster of options.

new-menu-options

From there we can now choose posts as menu items. Awesome, right?