Force sub-categories to use the parent category template

A couple of times in the last several years, I’ve needed sub-categories to inherit their parent’s archive template, but it’s just not something the Template Hierarchy supports. I’ve seen several plugins that tried and failed to do it, so finally I wrote a little filter that in my testing, works any number of levels deep, from sub-sub-categories to sub-sub-sub-categories. Enjoy!


function new_subcategory_hierarchy() {	
	$category = get_queried_object();

	$parent_id = $category->category_parent;

	$templates = array();
	
	if ( $parent_id == 0 ) {
		// Use default values from get_category_template()
		$templates[] = "category-{$category->slug}.php";
		$templates[] = "category-{$category->term_id}.php";
		$templates[] = 'category.php';		
	} else {
		// Create replacement $templates array
		$parent = get_category( $parent_id );

		// Current first
		$templates[] = "category-{$category->slug}.php";
		$templates[] = "category-{$category->term_id}.php";

		// Parent second
		$templates[] = "category-{$parent->slug}.php";
		$templates[] = "category-{$parent->term_id}.php";
		$templates[] = 'category.php';	
	}
	return locate_template( $templates );
}

add_filter( 'category_template', 'new_subcategory_hierarchy' );

Easy way to check if jQuery is already enqueued

Had a plugin wreaking some havoc today because it was overloading jquery.js with a minified, older version. Plugin authors: There’s a really simple way to check if jQuery or a jQuery library is already registered and enqueued. This covers really obscure edge cases where a plugin may have de-registered WordPress’s default scripts.

The offending code:

wp_register_script('myjquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', true, '1.6.4', false);
wp_enqueue_script('myjquery');

The fix:

// If jQuery isn't already enqueued, register and enqueue it
if ( ! jQuery ) {
	wp_register_script('myjquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', true, '1.7.2', false);
	wp_enqueue_script('myjquery');
}