Underscore, Backbone, and some basic JavaScript

Themes are awesome. Themes are amazing. Themes should be built with presenting user content in mind.

What happens when you introduce dynamic content? Live content. I know you may be wondering what I mean by this.

A little history

When I first began working with WordPress I knew the basics thing you needed to know about JavaScript. You know, the good old:

document.write( 'Hello world!' );
alert( 'How I am doing?' );
prompt( 'Is this working?' );

Yeah. Super simple things that interact with the browser. Didn’t get too deep into what JavaScript was or how to use it until the last few months. It has always been a goal of mine to learn more things about web development and this year was no different. I grabbed a few JavaScript books and began my quick journey into a world of hurt and a few headaches.

Yes, I got a few headaches and a few nosebleeds because some of the content was far too much to grasp. Some of it I still don’t fully understand but it is slowly making some sense. A lot of what helped was my short lived stint in what will now be a dead language. ActionSript. Yeah. I began that journey because I loved the idea of animating a site with Flash. Sorry. I was young and didn’t really know much better. As I said, this was before I really dove into what JavaScript was capable of doing.

Fast forward a bit and I had begun reading the JavaScript bible seventh edition. Later on I picked up JavaScript in 24 Hours, and a few other code related books. The most recent one being Eloquent JavaScript, Second Edition. I still have some reading to do on that one. I will say though my collection of reading has grown since I first began:

https://www.instagram.com/p/_nOXalML2B

Core usage

Now, as I’ve stated many times on this site, I will always recommend using core first. There are times when you do have to use other tools but that is because you really do have to use the right tool for the right job. When WordPress first introduced two neat little JavaScript libraries I was ecstatic. Backbone and Underscore JS. Both are great little tools that I feel are a great way of creating a theme.

One of the reasons I liked it being integrated was because it can resemble an MVC style of setup. I know there are some people out there who argue against it. I say it resembles in that it uses models and views. It does make it easier for many others to pick up if you come from another content management system other than WordPress. Yes, they do exist.

Yes, my list of reading materials just keeps growing and growing and this does include core code.

What next?

The next step is using all that knowledge and applying it to a theme. Yes, there are sliders out there that use JavaScript but using Backbone and Underscore in a theme would make for a super dynamic experience. Yes, there are other JavaScript libraries that can potentially be used but I’ll stick to learning these first.

Working with paginate_links

It is no secret that I try to advocate the use of core functions when possible. The idea of maintaining less code is a great one for any developer. It’s the old set it and forget mentality.

What I do see a lot of is the use of my_theme_pagination that uses get_pagenum_link in order to get all the page links. Yes it does use a core function but it uses it several times. Why not just use a core function that has been available since 2.1? Talk about way back, right? The best part is that you are given a few options when you use paginate_links.

The core code

Let us take a look at the core code. The function is found in the general-template.php file of the wp-includes folder. There are approximately 142 lines that make up this function. As you can see there is quite a bit of logic behind it to work. We will look at the key things. The first one being the array we can pass as an argument, and the second being the type key in that array.

You can use the function without passing anything to it and it will work. There is a reason for that. The $args parameter that can be passed gets merged with a few defaults. What are those, you ask? Here they are:

$defaults = array(
	'base' => $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below)
	'format' => $format, // ?page=%#% : %#% is replaced by the page number
	'total' => $total,
	'current' => $current,
	'show_all' => false,
	'prev_next' => true,
	'prev_text' => __('« Previous'),
	'next_text' => __('Next »'),
	'end_size' => 1,
	'mid_size' => 2,
	'type' => 'plain',
	'add_args' => array(), // array of query args to add
	'add_fragment' => '',
	'before_page_number' => '',
	'after_page_number' => ''
);

$args = wp_parse_args( $args, $defaults );

Quite a few options available to use. For the sake of this post we will focus on mostly on the type. There are three possible return types. They are array,list, and an empty value. We can see those towards the end of the function:

switch ( $args['type'] ) {
	case 'array' :
		return $page_links;

	case 'list' :
		$r .= "<ul class='page-numbers'>\n\t<li>";
		$r .= join("</li>\n\t<li>", $page_links);
		$r .= "</li>\n</ul>\n";
		break;

	default :
		$r = join("\n", $page_links);
		break;
}

It uses a switch statement to set the $r value that is ultimately returned. Yes, paginate_links returns and does not output any content. This is where we can actually take advantage of that.

Usage

Now with that in mind let us create some example usage, yeah? This is the part that gets fun! So we will take a look at using all three options and how they can be expanded or altered to suit your theme’s needs.

Array

Returning the array is one of the neater ways of using the function. The reason is that it returns an array of links. The amount of links is the amount of keys available for us to manipulate. Yes, we can style to our choosing. Let’s look at a sample return:

Array
(
    [0] => <span class='page-numbers current'>1</span>
    [1] => <a class='page-numbers' href='http://localhost/page/2/'>2</a>
    [2] => <a class='page-numbers' href='http://localhost/page/3/'>3</a>
    [3] => <span class="page-numbers dots">&hellip;</span>
    [4] => <a class='page-numbers' href='http://localhost/page/10/'>10</a>
    [5] => <a class="next page-numbers" href="http://localhost/page/2/">Next &raquo;</a>
)

What’s cool about that is you can see that by default you have the CSS classes page-number, current, and dots that you can use for some styling. Pretty awesome if you ask me. You can now expand upon that markup. A good way is by using the foreach to loop over and create your HTML markup. A quick example is:

$links = paginate_links( array( 'type' => 'array' ) );

echo '<div class="pagination col-6">';
foreach( $links as $link ){
	echo $link;
}
echo '</div>';

Yes, that is a super quick way of doing things but you get the idea. You can expand upon that to your heart’s content and add your needed classes or markup.

List

Another way is returning the list. An already HTML markup of our links in an unordered list. The returning text looks a little like:

<ul class='page-numbers'>
	<li><span class='page-numbers current'>1</span></li>
	<li><a class='page-numbers' href='http://locahost/page/2/'>2</a></li>
	<li><a class='page-numbers' href='http://localhost/page/3/'>3</a></li>
	<li><span class="page-numbers dots">&hellip;</span></li>
	<li><a class='page-numbers' href='http://localhost/page/10/'>10</a></li>
	<li><a class="next page-numbers" href="http://localhost/page/2/">Next &raquo;</a></li>
</ul>

What is super awesome about it is you can use just one line of code:

echo paginate_links( array( 'type' => 'list' ) );

Super awesome, right? The reason I love that is you can just leave that code and style it all. No special markup to worry about as it is already taken care of. You can use something like:

ul.page-numbers {
  clear: both;
  font-size: 1.4em;
  color: #deaf01;
}

ul.page-numbers li {
  display: inline-block;
}

It doesn’t have to be super crazy but you get the idea.

Empty value

Now for the simplest way of using the function.

echo paginate_links();

A lot of work, right? Super, super simple and you don’t have to worry about creating any extra markup. That is if you don’t want to. It returns a string of all the links and you can go about your business. If you really like super simple HTML markup then please use that.

User changes

Yes, we can have a user change a few of the things too if we want. Let’s take a quick look at how we can change the amount of links to show around the current page.

function jc_pagination(){
	echo paginate_links( 
		array(
		'show_all' => get_theme_mod( 'all-links', false ),
		'type' => 'list',
		'mid_size' => get_theme_mod( 'mid-links', 3 )
		)
	)
}

Pretty cool, right? With that get_theme_mod you can now have the user decide how many links will show before and after the current page. Yes, it is a minor touch but it can go a long way with some users.

Another template hierarchy post

Oh, the template hierarchy is a temptress. The reason being when themes create a new template it can work in really strange ways. A good example are the front-page and home templates. The tricky part is knowing when to use the right one. A far less common one is page templates.

Many like to use the naming convention of page-{template-name}.php but that can be a bad thing. The way the template hierarchy works is by looking through a list of file names to load but that is for pages and certain scenarios. Let’s take a look at how the template is actually loaded:

The following snippet is from the template loader file from core:

if ( defined('WP_USE_THEMES') && WP_USE_THEMES ) :
	$template = false;
	if     ( is_404()            && $template = get_404_template()            ) :
	elseif ( is_search()         && $template = get_search_template()         ) :
	elseif ( is_front_page()     && $template = get_front_page_template()     ) :
	elseif ( is_home()           && $template = get_home_template()           ) :
	elseif ( is_post_type_archive() && $template = get_post_type_archive_template() ) :
	elseif ( is_tax()            && $template = get_taxonomy_template()       ) :
	elseif ( is_attachment()     && $template = get_attachment_template()     ) :
		remove_filter('the_content', 'prepend_attachment');
	elseif ( is_single()         && $template = get_single_template()         ) :
	elseif ( is_page()           && $template = get_page_template()           ) :
	elseif ( is_singular()       && $template = get_singular_template()       ) :
	elseif ( is_category()       && $template = get_category_template()       ) :
	elseif ( is_tag()            && $template = get_tag_template()            ) :
	elseif ( is_author()         && $template = get_author_template()         ) :
	elseif ( is_date()           && $template = get_date_template()           ) :
	elseif ( is_archive()        && $template = get_archive_template()        ) :
	elseif ( is_comments_popup() && $template = get_comments_popup_template() ) :
	elseif ( is_paged()          && $template = get_paged_template()          ) :
	else :
		$template = get_index_template();
	endif;
	/**
	 * Filter the path of the current template before including it.
	 *
	 * @since 3.0.0
	 *
	 * @param string $template The path of the template to include.
	 */
	if ( $template = apply_filters( 'template_include', $template ) )
		include( $template );
	return;
endif;

A slight break down

That is a lot of code! Break it down and you will see that all it really does is check to see what type of page we are on and if we should load it. Let’s look at the first check:

if( is_404() && $template = get_404_template() ) :

The first thing it checks is whether or not the page to be displayed is an error page. In particular the 404 page. If it is and the $template is an existing file within either the child theme or parent theme then it will load it, other wise it will use the index.php file for the 404 template.

The file is retrieved with get_query_template. It doesn’t look like it because you see get_404_page() instead. Let’s look at that function below:

function get_404_template() {
	return get_query_template('404');
}

Great! Now you can see get_query_template() being called. What does that one do? Well, let us take a quick look:

function get_query_template( $type, $templates = array() ) {
	$type = preg_replace( '|[^a-z0-9-]+|', '', $type );

	if ( empty( $templates ) )
		$templates = array("{$type}.php");

	$template = locate_template( $templates );

	return apply_filters( "{$type}_template", $template );
}

Ok, it uses locate_template() to find the right $template, which in this case is the 404, and loads it if that file does exist. In this case it would be the 404.php file. Awesome. This can be seen from the locate_template() in core:

function locate_template($template_names, $load = false, $require_once = true ) {
	$located = '';
	foreach ( (array) $template_names as $template_name ) {
		if ( !$template_name )
			continue;
		if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {
			$located = STYLESHEETPATH . '/' . $template_name;
			break;
		} elseif ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {
			$located = TEMPLATEPATH . '/' . $template_name;
			break;
		}
	}

	if ( $load && '' != $located )
		load_template( $located, $require_once );

	return $located;
}

What’s pretty cool is the function first looks at the child theme’s files and if it finds it, returns that path

Other templates

But there are some that will use different files. Let’s take a look at the tag template hierarchy, shall we:

function get_tag_template() {
	$tag = get_queried_object();

	$templates = array();

	if ( ! empty( $tag->slug ) ) {
		$templates[] = "tag-{$tag->slug}.php";
		$templates[] = "tag-{$tag->term_id}.php";
	}
	$templates[] = 'tag.php';

	return get_query_template( 'tag', $templates );
}

As you can see, the first thing done is populate a variable with the queried object. That is so we can get the needed information. From there we use the tag’s slug as the first file to locate and load, the tag’s term_id as the second, and finally just tag as the filename to locate and load. What this means is that you can use tag-random.php for the random tagged post list. Or if you want a specific tag ID’s archives to look a certain way you can use the template tag-37.php to do that.

And more templates

Yes, there are a few more. If you look closely there are about 17 checks that are conducted. If all those fail the template that is loaded is the index template. I’ll list off the possible template files that a theme can potentially have.

  • 404
  • search
  • front-page
  • home
  • post-type archive
  • taxonomy
  • attachment
  • single
  • page
  • singular
  • category
  • tag
  • author
  • date
  • archive
  • comments-popup
  • paged

Do keep in mind those are some of the possible theme template files you could have. As you can see it can be a little tricky and at times odd when you use certain file naming conventions so try to keep that template hierarchy in mind when you are creating a theme that wants to use page templates.

So go explore those templates, break a theme, make a child theme, and perhaps share your errors on the forums to help others out.

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!

One theme reviewers point of view

How to begin? Well, back in 2012 I took the plunge and began my first theme review. It was a great experience because I got a chance to not only learn something but give back as well. I was already looking at themes because I love design. I wanted a different theme for my site and wanted to learn how to create themes. Of course, at the time there was only one in-depth tutorial on creating WordPress themes.

I’ll skip ahead a little bit and get to the part that may be juicy for some. After some time I was able to assign my own themes to review. This was a different time. The capabilities have changed a little over time. The process has – to a degree – changed. Some parts for the better.

Now, what I’m going to share may startle a few and rattle a few cages, but I’m okay with that. Reason is because I know I’m not alone when I feel this way. The process has slowed down too much. What used to take a week is now months. It’s not that reviewers don’t have time, it’s not that we don’t have the people, or the know-how. A lot of it is because there is so much to look over.

Today, I began to think about what needs to be looked over by one person. Yes, one person does a review of one theme. Then an admin looks over and sets the theme live. This process is being worked on.

Now, as I said, I actually counted all the requirements that need be addressed before any theme can be made live. Let’s count them by the sections they are listed:

  • Code: 6
  • Core functionality/features: 11
  • Presentation/Functionality: 1
  • Docs: 1
  • Language: 4
  • Licensing: 4
  • Naming: 2
  • Options/Settings: 4
  • Plugins: 2
  • Screenshot: 2
  • Security/Privacy: 4
  • Selling/Credits/Links: 2
  • Styles/Scripts: 6
  • Templates: 4

Wow! That is a lot to look over, right? Looking at the core functionality and features is a daunting one. Eleven items! Eleven! Add them all together and you have fifty-seven requirements that a theme must meet in order to meet the standard and pass. Now, that does not include the accessibility audit if a theme has the accessibility-ready tag listed. Yes, that too has a few requirements that need to be addressed.

So you can kind of see why it can take some time to conduct a theme review.

The other part is the time frame. Theme reviewers give up to a week for the theme’s author to submit a revised version of the theme with all the fixes. Does it always happen? No. A lot of the non-approved themes are because they didn’t reply in time or didn’t submit it in time. It does happen.

The downside is that some will submit a revised version on the last day before the “deadline,” and the process can then be resumed. The reviewer will look over the changes and make note of any missing requirements. As you can see the time can add up. As that happens, new themes are being submitted and sort of left there without a review.

You can see how they can quickly add up. Currently the wait time to have a reviewer assigned is about seven weeks. You read it right. Seven.

One thing that may make it faster is closing a ticket if the theme does not meet half of the requirements. Okay, great but not all themes have that many issues, correct? It is possible but how many are there that do?

Or perhaps not approve the theme if it doesn’t meet all the security and core requirements? Makes more sense to do something like that, right? At least then we can focus a little more on teaching about better practices and posting on the make blog about theme development.

Don’t get me wrong, this hasn’t stopped me from reviewing themes at all and it won’t. I just wanted to share a different point of view on an ever-evolving process.

Why theme documentation matters

Creating WordPress themes can be fun. Sharing them with everybody is even better. What happens when those users then ask you how to do something? Often times what is the simplest task to you may seem like a trip to Mordor for others. You don’t always know the person’s knowledge base when you share your theme. They could be a developer that began using BASIC when it was first introduced, or a person who has just picked up a book on how to build a website using WordPress.

What’s cool is we can meet both those worlds in the middle. One way is by using code comments. Code comments can make it easier for not only yourself but others to know what exactly the code is doing. A good example of this is the comment block below, taken from the wp_get_theme function:

/**
 * Gets a WP_Theme object for a theme.
 *
 * @since 3.4.0
 *
 * @global array $wp_theme_directories
 *
 * @param string $stylesheet Directory name for the theme. Optional. Defaults to current theme.
 * @param string $theme_root Absolute path of the theme root to look in. Optional. If not specified, get_raw_theme_root()
 * 	                         is used to calculate the theme root for the $stylesheet provided (or current theme).
 * @return WP_Theme Theme object. Be sure to check the object's exists() method if you need to confirm the theme's existence.
 */

Yes, it can look like a lot of information but not all your code has to be as robust as that. You can use simple documentation and still do just the same. While that does go for some developers, we cannot forget those that just want to use the theme and are possibly afraid of code, or don’t know how to code. Great! This is where other forms of documentation come in handy.

Types

There are other forms of documentation that you can use to your advantage. A few I like are:

  • Videos
  • Images
  • Readme file

Please note, images and videos may not always be view-able by all so you may have to take that into consideration on your path to documentation bliss. Now, let us explore those a little more.

Videos

I love me a good video. A video tutorial, that is. Now, your theme does not have to have a step by step video on how to setup every single option, or possibility your theme offers but you do want to have some of the basic, and perhaps most common things. A few examples are installing the theme, accessing your theme options, showing how to setup possible social links, or even using page templates. You don’t have to have audio but it does help. There are several programs out there that allow you to capture video and create video screen casts.

Images

Yes! Images can make a huge difference for many. Even better when they move. I am talking about gif images. They can be a great way to showcase a few steps without having to create a two minute video to show how to access extra options. If you have an image editing program it can be used to highlight what you want in order to emphasize parts of the image.

Readme File

The basic and standard file you need to include. Okay, that’s just me saying it but I’m sure there are more people who would agree with that statement. This is the part that really irks me because you can include some basic steps that can go a long way. A great example is setting up social link profiles. There are several ways of creating those and not all themes follow a standard. It is nice to know where to look and how to use it.

== Setting up social links ==
1. From Dashboard go to Appearance
2. Click Customize
3. Go down to Social section
4. Type username or ID ( depending on network )

Looks fairly simple, right? It can be for some but there may be others that may still get confused. Okay, we covered a simple setup but what happens when a user gets what they feel is an unexpected result?

What do I mean by this?

Let’s say the theme has a menu location at the bottom and you only want it to display one level of menu items. They may open a support request, thread, ticket, whatchumacallit, or what ever system of support you are using and ask why it isn’t showing all the menu items. This is where your theme’s documentation can come in super handy and essential. If it is a design choice then it should be stated in the documentation. A good way would be something like:

=== Limitations ==
* Featured images should be minimum 600 pixels wide and 400 pixels tall for best results
* The `footer-nav` menu location, by design, only displays one level of menu items
* The `ad-loc-1` widget area is only used in the page template `fullwidth-ads`
* If pages do not have a featured image set, the chosen header image will be used

Yes, even what sounds -or seems- strange is super helpful to the user of your theme. Knowing what the best size for an image is useful, just like knowing the right size of tire for your car or bicycle.

So please, please make sure you are documenting for not only yourself but for your users as well.

WordPress Static Front Page

Themes are a great way to showcase user content. Themes can often times add a bit of functionality to a site and that’s great! The hardest one to grasp is the use of a front page template. Yep, that can of worms. One of the common things I’ve noticed is authors creating two or more files with the same code. It hurts. The more common pattern of course is:

get_header();
	if ( get_option( 'show_on_front' ) == 'posts' ) {
        // If they want to show "Latests Posts"
		get_template_part( 'index', 'homepage' ) ;
	} elseif ( get_option( 'show_on_front' ) == 'page' ) {
        // otherwise we show the front page
		get_template_part( 'index' ) ;
	}
		
get_footer();

Or at least something close to that. They check in particular what the setting is. It’s this:

if ( get_option( 'show_on_front' ) == 'posts' ) { // code here }

That checks in particular what the user setting is. It basically says, if the user selected to use the latests post we run the following code. Usually it would be comprised of the amount of posts the user has set. Some like to show 5 post while some like showing 10. That doesn’t include stickies but I won’t get into that. That’s another can of worms not really worth opening right now.

There are several tutorials and other posts that are out there which can help you understand. One of my favorites is Chip Bennett’s on home page, front page, and templates. Really in-depth and a great starting point. If you don’t understand it, read it again. It will make sense eventually.

One thing I do find super weird is the way it checks. Not jump from the template hierarchy but in the way the query is as well. The core markup ( as of 4.3 ) is:

// @return bool True, if front of site.
public function is_front_page() {
    // most likely case
    if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
        return true;
    elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
        return true;
    else
        return false;
}

// @return bool True if blog view homepage.
public function is_home() {
	return (bool) $this->is_home;
}

It does two checks to make sure we are on the front of the site. Yeah a little odd but it does the trick. So, with that slight insight we can get a better understanding of how WordPress front-page, home, and index sort of fall into place.

Now, what can we do about it? The best method is using a filter. Yes. A filter. They are the lifeblood of any and all great themes and plugins. Use them like they are going out of style. Okay, perhaps a little extreme but they are super useful. I know that some people will be hesitant at first but once you get the hang of them and what to look for it will be a game changer for how you code.

The filter we’ll use is the get_query_template filter. This function/filter is found in the wp-includes/template file. The function is simplistic in nature and is filterable to your choosing. The code is:

function get_query_template( $type, $templates = array() ) {
	$type = preg_replace( '|[^a-z0-9-]+|', '', $type );

	if ( empty( $templates ) )
		$templates = array("{$type}.php");

	$template = locate_template( $templates );

	return apply_filters( "{$type}_template", $template );
}

So, let us break it down a little. This function accepts two arguments. The first one is required to be passed because it needs to know what file to look for otherwise it will give an error. The second one is an optional array of templates to look for. From there it will use locate_template to look first in the child theme for the file and if it doesn’t find it there it will use the parent folder to locate the template. Finally, we have our filter!

This is the fun part. In order to use the filter, we first have to know what template we would like to override. In our case it is the front-page.php; though it does something a little odd, in that it removes the - so we need to use frontpage as the template name. So the filter hook would look like:

add_filter( 'frontpage_template', 'jc_frontpage_template' );

Super simple, right? Now to write out the logic, or our callback function. In that function all we have to return is a string of where our replacement file is. Let’s say that we have a landing page that we would like to use. Just don’t forget to document that otherwise people may get confused on the unexpected behavior. In order to do so we can use something like:

function jc_frontpage_template( $template ){
	if ( is_home() ){
		get_home_template();
	} else {
		return locate_template( 'templates/landing.php' );
	}
}

Pretty sweet, right? I think so. So, go, explore those filters, break things and learn from it.

Today I ran into a bit of an internal debate. This is something that has driven me crazy for the longest time and this time I’m speaking about it.

Having an “upsell” theme in the WordPress theme repository. Quite frankly, I’m tired of it. Not only is it more code to look over but an inconvenience to the user. A commonality is the phrase:

This option available in PRO Version.

It does get linked to the site where they can purchase the theme. I don’t like it. Often times it is because that’s all the setting/control has. If I wanted to look at dummy controls I’d go to the toy store and just play with the toys and never purchase a thing. It is like window shopping for themes only with a banner over the window.
pro-versionAs you can see from the image, it is pointless to even have a pro version with nothing to control. I will never understand that. It is like having a car radio button that does nothing.

Yes, I made that comparison. It really is pointless.

I know there are some out there that may already be wanting to ask how to upsell the theme instead then. Simple. The theme’s about page.

Yes, themes can have them and should have them. What I don’t like is that there are several that link to just a demo site. What’s the point? Yes, I understand you want to demonstrate what the theme can do but what I’m more interested in is what the differences are between the free version and the premium/pro/ultra/supreme/deluxe version you are offering.

When I look to purchase a new camera I look for the information about the camera; I’ve already seen what it can do, I want to know more. What size sensor, what type of sensor, pixel density, lowest ISO, highest ISO, what accessories I can purchase for it, just to name a few.

So, if you are a theme shop in the WordPress theme repository, I urge you to drop all your upsell things that do nothing. You are hurting your users by subjecting them to unusable options.

Child themes are good

If you’ve been following me for some time you will know that I will always tell people to use a child theme when they want to make any modifications. There are times when it will not be needed because of the amount of code you are going to be changing.

Yes, that is when you have just created a fork of the theme. That’s for some other time because what this post is about is dealing with child themes and bundled themes.

As you can see, currently this site is using Twenty Sixteen as the parent theme. I created a child theme and am using the template hierarchy to do some of my bidding for my downloads page.

At the time of writing, the child theme is only using 5 files. The functions file, a front page file, download archive file, download content file, and the stylesheet.

I’m loading the style by using:

add_action( 'wp_enqueue_scripts', function(){
   wp_enqueue_style( 'parent', get_template_directory_uri() . '/style.css' );
   wp_enqueue_style( 'child', get_stylesheet_uri() ); 
});

As you can see I’m using an anonymous function in order to load the styles. If you are going to use that code, make sure your hosting company is running at least PHP version 5.3 or higher, otherwise you will run into issues.

The other part I wanted to share was how I’m loading all the downloads on the archive page. Super small snippet that uses the pre_get_posts filter to achieve this:

add_filter( 'pre_get_posts', function( $query ){
   if(!is_admin() && $query->is_post_type_archive( 'download' ) && $query->is_main_query() ){
       $query->set( 'posts_per_page', -1 );
   }
    return $query;
});

Yes, another anonymous function. As you can see just a few lines of code. I don’t need it to be a lot at the moment. The only reason is because I’m slowly adding more downloads. Once I get to a specific number I’ll use AJAX in order to load more downloads so it won’t kill slow internet connections. I may just do that in the following weeks on my downtime.

Projects on hold

Not long ago I posted about by small widget:

Random project

It felt good. I’ve been slowly working on random things here and there but never really bothered with actually sharing them. I’ve gotten a little better at it ever since I began using the latest version of core and the Twenty Sixteen theme. Yes:

Temporary look change

There are other side projects I would like to get to aside from code. A good example would be my random blog. I haven’t done one in a long time and I think I am overdue for one. I think it is time to charge some batteries and get my tripod ready.