Three sliders, one option, and a few tears later

Yes, sliders have a special place in my heart. Granted a super tiny place in my theme reviewer’s heart. Now, I’ve created a few tutorials, guides, resources, links, what you will on this site in order to share some of my insights into WordPress theme development and perhaps some WordPress theme reviews along the way.

There are a lot of things I have learned and a lot of things I had to learn. I think the biggest takeaway from this post will be that integrating a slider plugin to a theme is fairly easy to do but a pain in the butt to fully integrate.

So, let’s get the show on the road!

First steps

Okay, we need to figure out first what slider we would like to play nice with, right? I chose sort of at random three different plugins that all create sliders.

I was going to use Meta Slider but they actually have a fairly extensive documentation section on theme integration. So major kudos for them on providing those code snippets!

As you can see we have our three sliders to choose from and now we need to determine if they are active or not. I know some will want to use is_plugin_active() but I will tell you not to. The reason for not doing so is so that you don’t load an extra file. So instead we will use some basic PHP functions to check.

function jc_get_sliders(){
	$sliders = array();
	
	if ( class_exists( 'Soliloquy_Lite' ) ){
		$sliders['soliloquy'] = 'Soliloquy';
	}
	
	if ( function_exists( 'huge_it_slider_activate' ) ){
		$sliders['huge_it_slider'] = 'Huge IT Slider';
	}
	
	if ( function_exists( 'wd_slider' ) ){
		$sliders['wds'] = 'Slider WD';
	}
	
	return $sliders;
}

I know some of you are wondering why I chose to use the class and functions I chose to check for. Those are the classes and functions those respective plugins use when they are activated. If those plugins are not active they will not exist.

Now that we have our options for plugins we can create our theme customizer options.

add_action( 'customize_register', function( $wp_customize ){
	// Set up the section
	$wp_customize->add_section( 'slider-section',
		array(
		'title' => __( 'Select a slider', 'jc-domain' ),
		'priority' => 30,
		) );
	// register the setting
	$wp_customize->add_setting( 'slider-type',
		array(
		'default' => '',
		'sanitize_callback' => 'jc_valid_slider',
		) );
	// register the setting's control but only output if those sliders exist
	$wp_customize->add_control( 'slider-type-input',
		array(
		'label' => __( 'Select the slider to use', 'jc-domain' ),
		'settings' => 'slider-type',
		'section' => 'slider-section',
		'type' => 'select',
		'choices' => jc_get_sliders(),
		'active_callback' => 'jc_sliders_exist'
		) );
	// register the setting
	$wp_customize->add_setting( 'slider-id',
		array(
		'default' => '',
		'sanitize_callback' => 'absint',
		) );
	// register the setting's control but only output if those sliders exist
	$wp_customize->add_control( 'slider-id-input',
		array(
		'label' => __( 'Input the ID of the slider you would like to use', 'jc-domain' ),
		'settings' => 'slider-id',
		'section' => 'slider-section',
		'type' => 'number',
		'active_callback' => 'jc_sliders_exist'
		) );
	
});

Great! Now you can see that I am using an active_callback for the controls. This is so that the section will not show if there are no active plugins to choose from. That means we have to create that callback. Fairly simple:

function jc_sliders_exist(){
	if ( !empty( jc_get_sliders() ) )
		return true;
	return false;
}

As you see we can utilize the first function we created that gets the sliders to our advantage. If the array is not empty we return true, otherwise we return false. Straight-forward. Now, you may notice one function we may need to create and that is jc_valid_slider. This is what will check if the option is a valid option and return it. So, let’s create that shall we:

function jc_valid_slider( $value, $control ){
	return ( array_key_exists( $value, jc_get_sliders() ) ) ? $value : $control->default;
}

Yes, you can see we are still using jc_get_sliders() to get our values. No need to create another wheel when we already have one, right?

The output

I know you are now wondering, “But Jose, how will you display the slider?” Well, let me show you how! We use get_theme_mod() and do_shortcode() with a quick check to output our slider.

add_action( 'jc_slider_area', 'jc_create_slider' );
function jc_create_slider(){
	// get the setting for the type of slider
	$type = get_theme_mod( 'slider-type' );
	// get the setting for the ID of the slider to use
	$id = get_theme_mod( 'slider-id' );
	
	// Check if we have chosen a slider
	if( !$type ){
		return;
	}
	
	echo do_shortcode( "[$type id='$id']" );
}

Great! But I know you are probably wondering why I’m using an action hook rather than creating a function and calling it. What’s super cool about using a hook is that this can be extended or removed with a child theme or functionality plugin. Super great way of making your theme extendable and child theme friendly. So, in the last step all we need to do is create that action hook.

<?php do_action( 'jc_slider_area' ); ?>

By adding that to where you want the slider to show, you can create a great hook for any theme developer to utilize.

Minor note

If you hadn’t noticed, I registered the customizer settings using an anonymous function. This will work on PHP versions 5.3 and higher so please make sure you are aware of what your environment you are developing for. So go, explore and try to break things along the way!

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.

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.

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.

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.

Uploading and updating your theme

It’s no secret I love doing theme reviews. When I get a chance. The past couple of weeks though I’ve only been able to do one a week if I’m lucky. I do read the theme-reviewers emails when I open my inbox but of course that just isn’t enough.

Background

If you didn’t already know for the last year I’ve been stating that I am working on a theme to submit. Yes and no. The biggest thing I’ve actually been working on is a personal theme. for this site. I’ve looked at many themes and have even thought about purchasing a theme from an established, and reputable theme foundry. As you can tell I chose to use the Displace theme.

For the time being I like and it does the job. I’ve thought about modifying it but want to create my own. Maybe down the road. We’ll see. I’m getting a little sidetracked so we’ll talk about the issue at hand. Updates and the review process.

Uploading a new theme

themes-directory

The process is actually quite simple. One of the first things you want to do is go to the themes directory. As you can see from the image on the right hand side the welcome screen showcases a few featured themes and on the right hand column there are three sub-sections: Popular, Newest and Recently updated.

You will want to login with your WordPress.org username and password. After you have done that you have, and I mean have to, read more about having your theme hosted in the repository. I cannot emphasize that part enough, either. In particular the guidelines to getting your theme accepted.

That little about page is very crucial and does look a little like:

themes-directory-2
Read! And I mean read this page.

Yeah, it does seem a little daunting but it is fairly simple and straight-forward. Some information about theme-tags, guidelines and why you would want your theme in the repository.

So, you’ve signed in and want to upload your theme. You go to the upload section by clicking the Theme Authors link and you are taken to the upload screen. This is the crucial one you will want to store not only in your bookmarks but in your head as well. This page is what will create a new Trac ticket with your theme so that an actual human being will go over your code and give you feedback and hopefully approve your theme.

A ticket?

You read that right. A ticket. You will receive an email confirmation with that ticket number. If that doesn’t happen you may want to contact the theme-reviewers list and I’m pretty sure at least one person will be able to help you out.

themes-trac-intro

The next stage is the review process. When I started doing reviews it was a little tedious, to say the least, only because so much of the process wasn’t as automated as it is now.

What a reviewer would do is login to the Trac for WordPress themes, go to the report, as demonstrated in the next image, and see if there were any other tickets that have been submitted using the same username/theme and close the tickets. The reviewer would then conduct the review with the most current version of the theme.

trac-ticket-queues

What next?

The next thing you will be getting is feedback. Good, bad and maybe even some ugly. We don’t always like to hear the truth but let’s face it. We don’t always do our best the first time around. I know I don’t.

previously-approvedFrom here on out it will be a human being, an actual living, breathing, eating, human being that will read over your lines of code. That person will read every character and see every image you used to create that WordPress theme. And hopefully, just hopefully it will pass inspection. The key here is communication. Get a dialogue between both you and the reviewer. A great example is a review I did a few weeks ago to the Customizer theme as seen on the image to the left.

Now, I know you’re wondering why such a long list of tickets that developer has. At least those that looked at the image. That was because some of those are updates. If you’re not asking how you update your theme then I’m not sure we can keep talking. In real life. I kid of course.

In order to update not only your theme in the repository, but in the theme trac you will want to visit the upload page once more.

upload-signedAfter you have signed in, naturally, you will head back to the upload page, make sure you bump the version of your theme in your stylesheet and you will be on your way to sharing with the WordPress community.

 Final thoughts

As I said the key is communication. Talk to the person conducting the review and the developer. You would be amazed about what both parties can learn and you also may make a new connection in the end.

Creating a custom comment list

What?

Comments. That is the topic. As some may know I’m in the middle of creating a WordPress theme to submit to the repository. I want this theme to not only pass but to pass with flying colors. I followed about as close to how the default themes are but have also integrated some from themes I have reviewed and added a bit of my own style, of course.

What started this?

What really initiated this was the default theme for WordPress 3.6: Twenty Thirteen. Previous default versions all passed a certain set of arguments and made a callback function in order to display the comments rather than have WordPress handle it. Wait? You mean to tell me that I can let WordPress do the coding for me? Yes. If you don’t like having control of how to structure your code. Twenty thirteen lets WordPress handle the coding of the comment list.

Callback?

Yes, a callback function. Simple and you have more control of how the code is structured and displayed. The function that handles this is:

wp_list_comments()

All that is needed now is some arguments:

$defaults = array(
    'walker'            => null,
    'max_depth'         => '',
    'style'             => 'ul',
    'callback'          => null,
    'end-callback'      => null,
    'type'              => 'all',
    'page'              => '',
    'per_page'          => '',
    'avatar_size'       => 32,
    'reverse_top_level' => null,
    'reverse_children'  => '',
    'format'            => 'xhtml', /* or html5 added in 3.6  */
    'short_ping'        => false, /* Added in 3.6 */
);
wp_list_comments ( $defaults );

Now, the thing that creates the comments is the callback. It tells WordPress to run the default code if no argument is passed. If there is one, then WordPress will look for that function and use that instead. In Twenty Twelve it was:

wp_list_comments( array(
    'callback' => 'twentytwelve_comment',
    'style' => 'ol'
     ) );

In the Twenty Thirteen theme it actually uses the default HTML5 markup by not setting a callback function and using the new argument:

'format' => 'html5'

This tells WordPress to use the HTML5 markup for the comment which is:

<article class="comment-body">
 <footer class="comment-meta">
 <div class="comment-author vcard"></div><!-- .comment-author -->
 
 <div class="comment-metadata">
 <a href="">
 <time></time>
 </a>
 <span class="edit-link">Edit</span>
 </div><!-- .comment-metadata -->

 <p class="comment-awaiting-moderation"></p>

 </footer><!-- .comment-meta -->

 <div class="comment-content"></div><!-- .comment-content -->

 <div class="reply"></div><!-- .reply -->

</article><!-- .comment-body -->

Keep in mind that is the very simplified version without any WordPress comment template tags. Just straight HTML5 markup. Some people don’t mind using that while others like to have more control and would like to style in a different way. In order to do that we have to pass an argument to the callback function argument.

Enter the callback

This is why you want to use a callback function to create and style the comment. In order to do this we pass the argument

'callback' => 'my_theme_comment'

in our array of arguments much like Twenty Twelve does. Next we have to create the actual function that will house our newly created and customized comment with custom markup. Where that function resides is entirely up to you.

Once we have created the function we can start with all the markup and comment template tags we so desire. I personally like to keep things fairly simple and just have the comment author, date and text. Often my code looks like:

function custom_comments( $comment, $args, $depth ) {
    $GLOBALS['comment'] = $comment;
    switch( $comment->comment_type ) :
        case 'pingback' :
        case 'trackback' : ?>
            <li <?php comment_class(); ?> id="comment<?php comment_ID(); ?>">
            <div class="back-link">< ?php comment_author_link(); ?></div>
        <?php break;
        default : ?>
            <li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
            <article <?php comment_class(); ?> class="comment">

            <div class="comment-body">
            <div class="author vcard">
            <?php echo get_avatar( $comment, 100 ); ?>
            <span class="author-name"><?php comment_author(); ?></span>
            <?php comment_text(); ?>
            </div><!-- .vcard -->
            </div><!-- comment-body -->

            <footer class="comment-footer">
            <time <?php comment_time( 'c' ); ?> class="comment-time">
            <span class="date">
            <?php comment_date(); ?>
            </span>
            <span class="time">
            <?php comment_time(); ?>
            </span>
            </time>
            <div class="reply"><?php 
            comment_reply_link( array_merge( $args, array( 
            'reply_text' => 'Reply',
            'after' => ' <span>&amp;amp;darr;</span>', 
            'depth' => $depth,
            'max_depth' => $args['max_depth'] 
            ) ) ); ?>
            </div><!-- .reply -->
            </footer><!-- .comment-footer -->

            </article><!-- #comment-<?php comment_ID(); ?> -->
        <?php // End the default styling of comment
        break;
    endswitch;
}

And there we have a custom comment that will be used instead of the default WordPress one.

Creating a sticky post slider

Brief background

Creating a slider is simple. For some. In WordPress there are a lot of ways to creating a post slider, image slider, category slider and just about any type of slider you could possibly imagine. The one I wanted to share is creating one with sticky posts. You know the ones that you have to pick from the slightly hidden options.

Make post sticky

Yeah. That little guy. The way WordPress handles sticky post is by putting them on the front page and keeping them on top regardless of when it was posted. A good example is the quick image I created to help illustrate.

The requirements

WordPress has plenty functions and plenty of ways of getting the required posts. One way of getting posts is using get_posts() but that isn’t the method I’ll be using. I’ll be using the WP_Query and alter it just a little bit. No, not with query_posts because that will just cause the world to implode. Okay, not really but there are several other reasons not to use that function.

The steps

In order to have a good functional featured post slider we first need to layout the steps needed. What I did initially was make a quick list of the steps.

  1. Get the posts
  2. Check if there are any ‘sticky’ posts
  3. If there are then run our code
  4. Ignore sticky posts in regular feed
  5. Drink up

The code

Now that we have our logic we can get started.

The first thing we have to do is get all the posts that are set to be sticky. We create and array to hold these.

$stickies = get_option( 'sticky_posts' );

We need to count how many posts there are and we’ll store that as a variable so we can use it later on.

$count = count( $stickies );

Now that we have an array and the total we can start a new query for only those posts. The way we do this is by creating a new WP_Query and passing some arguments. So we’ll create these arguments and name our newly created object of posts $featured. It can be whatever you want it to be. If you are submitting to the WordPress repo then prefix it with your theme or equivalent.

$args = array(
	'post__in'       => $stickies,
	'posts_per_page' => 3,
	'post_type'      => 'post',
	'nopaging'       => true
	);
$featured = new WP_Query( $args );

Now that we have our new object filled with posts we can run our code with the newly created query. But wait! When WordPress is first installed there are no sticky posts so then how do we check for that? Simple. Remember that we stored the value into a variable called $count? We’ll use that. We’ll use an if statement to run our code. If there are no posts then we’ll begin the newly created WordPress loop.

if ( $count > 0 ) {
  // run WordPress loop using $featured
}

Sounds simple now that we have it all together, right? Now we can create the loop and fill it with all the goodies and information we want using template tags. Don’t forget to use wp_reset_postdata() to reset our post data. There is one last thing we must do to get it all working right and that is hooking to pre_get_posts.

What?!

One more thing?

Yes, one last thing. I know a bit of a curveball but this is what will prevent the doubling of sticky posts. What we have to do is add just a few lines of code to our functions file of our theme.

add_action( 'pre_get_posts', 'my_awesome_theme_pre_posts' );
function my_awesome_theme_pre_posts( $query ){
    if ( is_home() ){
        $query->set( 'post__not_in', get_option( 'sticky_posts' ) );
    }

    return $query;
}

Now that we have that done we have our final code snippet:

// Create array of all the sticky_posts
$stickies = get_option( 'sticky_posts' );

// Count how many there are, if any
$count = count( $stickies );

// Create a set of arguments to pass
$args = array(
	'post__in'       => $stickies,
	'posts_per_page' => 3,
	'post_type'      => 'post',
	'nopaging'       => true
	);

$featured = new WP_Query( $args );

// If there is one or more sticky post we create our new slider
if ( $count > 0 ) : ?>
<section class="featured" id="featured-slider">
    <?php while( $featured->have_posts() ) : $featured->the_post(); ?>
    <article <?php post_class( 'featured' ); ?> id="post-< ?php the_ID(); ?>">
        <h1 class="featured-title"><?php the_title(); ?></h1>
        <div class="content"><?php the_content(); ?></div>
        <div class="content"><?php wp_link_pages(); ?></div>
        <footer class="meta">Posted: <?php the_time( get_option( 'date_format' ) ); ?></footer>
    </article>
    <?php endwhile; wp_reset_postdata(); ?>
</section><!-- end of our featured article slider -->
<?php endif; // end the featured posts ?>

Enjoy

And done! For the most part since we need to add interaction but I’ll let you pick out what to use since there are plenty of jQuery slider plugins to help with that.