Make WordPress subcategories to use parent category template

subcategories templateWell today I’m going to bring you new snippet. For example, let’s say you are using the posts for various purposes like questions, pools, articles and reviews. To sort it out you will need different categories. Of-course now you need to design different category layout. This is done using the slug preference, like: category-questions.php, category-pools.php, category-reviews.php in your template folder etc.

The whole idea is great and it will work, but things goes wrong when you add subcategories to any of parent (main) categories like on our example questions, pools, reviews… To understand it we need to know WordPress hierarchy

The category/archive template hierarchy in WordPress.

category-{slug}.php
category-{id}.php
category.php
archive.php
index.php

To understand to this “issue” even that is not, we have to look at default get_category_template() function witch is in WordPress since 1.5 update.

Default WordPress GET category template function

[php]
function get_category_template() {
$category = get_queried_object();

$templates = array();

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

return get_query_template( ‘category’, $templates );
}
[/php]

If we watch closer to the get_category_template() function we can’t miss that it doesn’t look up hierarchy at all so the new function should do exactly that.

What this means? If there is a category named reviews, and the ID 13, then category archive will first look for the file category-reviews.php , then for the file category-13.php. If those php files are missing it will search for category.php. For example it also doesn’t exist, it will continue to archive.php and if there are lack of archive.php goes for the index.php to display the category content.

With this logic it’s obvious that the subcategory of category reviews, actually hosting (http://website.com/category/reviews/hosting) won’t load category-reviews.php.

So this snippet is telling WordPress to recognize if there are parent’s category template (category-reviews.php) available to use it as child’s template too.

Make subcategories to use parent category template

[php]
/****** Make subcategories to use parent category template ******/
/**
* Snippet Name: Make WordPress subcategories to use parent category template
* Snippet URL: http://wperror.com/make-subcategories-to-use-parent-category-template.html
*/
function wpe_subcategory_template() {
$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’, ‘wpe_subcategory_template’ );
[/php]

Add Thumbnails in Manage Posts/Pages and Other Post Types

Hi there, here we go again! For today I’ve prepared you this simple ready to copy functions to display to the Manage/Edit Post and Pages and my custom taxonomy Downloads a new column with the thumbnail preview.
Thumbnails in Manage Posts

This snippet will first search for thumbnail and it’s id, but if fail then look for attachment used in the image there are no thumbnails on the posts to call a image[0], or the first image in the post, page or download type.

The default thumb size is 55px x 55px but you can easy change it on this snippet code. Simply you just have to edit $width and $height values. The same worth for custom post type selection, just edit this part of a code add_theme_support(‘post-thumbnails’, array( ‘post‘, ‘page‘, ‘download‘ ) );.

Add Thumbnails in Manage Posts/Pages

[php]
/****** Add Thumbnails in Manage Posts/Pages List ******/
/**
* Snippet Name: Add Thumbnails in Manage Posts/Pages and Other Post Types
* Snippet URL: http://wperror.com/add-thumbnails-in-manage-postspages-and-other-post-types.html
*/
if ( !function_exists (‘AddThumbColumn’) && function_exists (‘add_theme_support’) ) {

// for post and page
add_theme_support (‘post-thumbnails’, array( ‘post’, ‘page’ ) );

function AddThumbColumn ($cols) {

$cols[‘thumbnail’] = __(‘Thumbnail’);

return $cols;
}

function AddThumbValue ($column_name, $post_id) {

$width = (int) 35;
$height = (int) 35;

if ( ‘thumbnail’ == $column_name ) {
// thumbnail of WP 2.9
$thumbnail_id = get_post_meta( $post_id, ‘_thumbnail_id’, true );
// image from gallery
$attachments = get_children( array(‘post_parent’ => $post_id, ‘post_type’ => ‘attachment’, ‘post_mime_type’ => ‘image’) );
if ($thumbnail_id)
$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
elseif ($attachments) {
foreach ( $attachments as $attachment_id => $attachment ) {
$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
}
}
if ( isset($thumb) && $thumb ) {
echo $thumb;
} else {
echo __(‘None’);
}
}
}

// for posts
add_filter( ‘manage_posts_columns’, ‘AddThumbColumn’ );
add_action( ‘manage_posts_custom_column’, ‘AddThumbValue’, 10, 2 );

// for pages
add_filter( ‘manage_pages_columns’, ‘AddThumbColumn’ );
add_action( ‘manage_pages_custom_column’, ‘AddThumbValue’, 10, 2 );
}
[/php]

Add custom post types to archives page

CPT ArchivesAfter we have added custom post types snippet into our functions.php we expect that our new articles under the custom post type to appear on archive pages, but they will not. It’s very logical from the developers side, WordPress maintain that sorting archives is for normal post types “posts”, and adding custom post types into categories and post_tags requires some custom code.

So, if you’d like your custom post types to show up in archive listings for your site’s standard tags and categories you can add the following code to your functions.php file:

Add custom post types to archives

[php]
/**
* Snippet Name: Add custom post types to archives page
* Snippet URL: http://wperror.com/add-custom-post-types-to-archives-page.html
*/

function add_custom_types_to_tax( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars[‘suppress_filters’] ) ) {

// Get all your post types
$post_types = get_post_types();

$query->set( ‘post_type’, $post_types );
return $query;
}
}
add_filter( ‘pre_get_posts’, ‘add_custom_types_to_tax’ );
[/php]
Still if you wish to display only specific custom post types into archive pages of tags and categories you can replace the line $post_types = get_post_types(); with $post_types = array( ‘post’, ‘your_custom_type’ );.

Create a Custom Post Type Download

Custom Post Type Download

Nowadays when WordPress become most used CMS, users are searching for various improvements for their sites. WordPress have ability to add custom post types and taxonomies easily with some snippet code in your functions.php file, or even easier trough the various plugins witch brings you this and similar options like custom taxonomies, custom meta boxes, fields etc. All those snippets/add-ons can quickly turn your WordPress site into well-featured CMS.

One of the easiest ways to add custom post type is trough the free WordPress plugin Custom Post Type Maker. Personally I preffer adding them with snippet code so I brings you simple snippet code that is ready to paste into functions.php file.

Custom Post Type Snippet

[php]
/**
* Snippet Name: Create a Custom Post Type "Download"
* Snippet URL: http://wperror.com/create-a-custom-post-type-download.html
*/

add_action( ‘init’, ‘register_cpt_download’ );
function register_cpt_download() {
$labels = array(
‘name’ => _x( ‘Downloads’, ‘download’ ),
‘singular_name’ => _x( ‘Download’, ‘download’ ),
‘add_new’ => _x( ‘Add New’, ‘download’ ),
‘add_new_item’ => _x( ‘Add New Download’, ‘download’ ),
‘edit_item’ => _x( ‘Edit Download’, ‘download’ ),
‘new_item’ => _x( ‘New Download’, ‘download’ ),
‘view_item’ => _x( ‘View Download’, ‘download’ ),
‘search_items’ => _x( ‘Search Downloads’, ‘download’ ),
‘not_found’ => _x( ‘No downloads found’, ‘download’ ),
‘not_found_in_trash’ => _x( ‘No downloads found in Trash’, ‘download’ ),
‘parent_item_colon’ => _x( ‘Parent Download:’, ‘download’ ),
‘menu_name’ => _x( ‘Downloads’, ‘download’ ),
);
$args = array(
‘labels’ => $labels,
‘hierarchical’ => true,
‘supports’ => array( ‘title’, ‘editor’, ‘excerpt’, ‘author’, ‘thumbnail’, ‘trackbacks’, ‘custom-fields’, ‘comments’, ‘revisions’, ‘page-attributes’ ),
‘taxonomies’ => array( ‘category’, ‘post_tag’ ),
‘public’ => true,
‘show_ui’ => true,
‘show_in_menu’ => true,
‘menu_position’ => 5,
‘menu_icon’ => ”,
‘show_in_nav_menus’ => true,
‘publicly_queryable’ => true,
‘exclude_from_search’ => false,
‘has_archive’ => true,
‘query_var’ => true,
‘can_export’ => true,
‘rewrite’ => true,
‘capability_type’ => ‘post’
);
register_post_type( ‘download’, $args );
}
[/php]

The known issue when the custom post types are created trough the snippet is that WordPress does not automatically take your custom post types and add them to the archive pages for existing taxonomies like categories or post_tags. Because of that we have prepared you another snippet for adding custom post types to archives page with snippet too.

Limit search to post titles only

search post titlesI know that this is not something new on scene but anyway there snippet to limit search to the post titles only.

Yesterday client witch for I was working on a real estate template asked me: Is there a way to limit search to post titles only?

Here are the snippet that I’ve used to enable search for post titles only.

This search filter could be use various combinations to query any other custom post type. For example we could query custom post type “Portfolio” simply by replacing snippet with this code: $query->set(‘post_type’, ‘portfolio’);

Filter search to posts only

[php]
/**
* Snippet Name: Limit search to posts
* Snippet URL: http://wperror.com/limit-search-to-post-titles-only.html
*/
function SearchFilter($query) {
if ($query->is_search) {
$query->set(‘post_type’, ‘post’);
}
return $query;
}
add_filter(‘pre_get_posts’,’SearchFilter’);
[/php]

Filter search to titles only

[php]
/**
* Snippet Name: Limit search to titles only
* Snippet URL: http://wperror.com/limit-search-to-post-titles-only.html
*/
function __search_by_title_only( $search, &$wp_query )
{
global $wpdb;

if ( empty( $search ) )
return $search; // skip processing – no search term in query

$q = $wp_query->query_vars;
$n = ! empty( $q[‘exact’] ) ? ” : ‘%';

$search =
$searchand = ”;

foreach ( (array) $q[‘search_terms’] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE ‘{$n}{$term}{$n}’)";
$searchand = ‘ AND ‘;
}

if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = ”) ";
}

return $search;
}
add_filter( ‘posts_search’, ‘__search_by_title_only’, 500, 2 );
[/php]

As you can see, the first snippet is used to limit search function to the posts only, while the other search by title only.

Customize WordPress Tag Cloud Widget

Yesterday I was working on developing custom template for one Czech guy. One of the things from the list is to do was customizing the WordPress Tag Cloud Widget for Categories. During this project there was a lot specific request, unique coding and tricks witch I’m gonna explain you here at WPError in next several days.

I was supposed to setup the Tag Cloud Widget to show only 11 categories by count from the categories list. Okay it might looks strange as we are talking about Tag cloud widget and categories in cloud, but let me explain it for you a little. The tag cloud is old WordPress function, but since WordPress 2.8 update it’s upgraded and it’s working with all taxonomies witch are by default tags and categories plus any other custom taxonomies.

[php]
// Parameters accepted by tag cloud widget
// @url http://codex.wordpress.org/Function_Reference/wp_tag_cloud
$args = array(
‘smallest’ => 8,
‘largest’ => 22,
‘unit’ => ‘pt’,
‘number’ => 45,
‘format’ => ‘flat’,
‘separator’ => \\"\n\\",
‘orderby’ => ‘name’,
‘order’ => ‘ASC’,
‘exclude’ => null,
‘include’ => null,
‘topic_count_text_callback’ => default_topic_count_text,
‘link’ => ‘view’,
‘taxonomy’ => ‘post_tag’,
‘echo’ => true,
‘child_of’ => null
);
[/php]

Limit Tag Cloud Widget to 11 items and Order by Count for Categories

Tag Cloud Widget

To achieve the following widget look I was suposed to edit few tag cloud parameters:
1. Customize Font Size of items (smallest and largest)
2. Customize the order
3. Custom taxonomy select
 
 
 
 
 
 

#1 working tag cloud widget code with array

[php]
add_filter(‘widget_tag_cloud_args’,’set_number_tags’);
function set_number_tags($args) {
$args = array(‘smallest’ => 11, ‘largest’ => 11, ‘number’ => 11, ‘orderby’ => ‘count’, ‘taxonomy’ => ‘category’);
return $args;
}
[/php]

#2 working tag cloud widget code without array

[php]
add_filter( ‘widget_tag_cloud_args’, ‘wpe_widget_tag_cloud_args’ );
function wpe_widget_tag_cloud_args( $args ) {
$args[‘smallest’] = 11;
$args[‘largest’] = 11;
$args[‘number’] = 11;
$args[‘orderby’] = ‘count';
$args[‘taxonomy’] = ‘category';
return $args;
}
[/php]

Here bellow I will write and explain you few other WP Tag Cloud snippets witch you can simply use simply by past into function.php file.

Changing the Number of Tags to Display on Widget

[php]
add_filter( ‘widget_tag_cloud_args’, ‘wpe_widget_tag_cloud_args’ );
function wpe_widget_tag_cloud_args( $args ) {
$args[‘number’] = 20;
return $args;
}
[/php]

Changing the Largest and Smallest Font Sizes

Keys that we are going to use are smallest, largest and unit. As we want to display pixels on font size instead of points we have to use unit key aswell.
[php]
add_filter( ‘widget_tag_cloud_args’, ‘wpe_widget_tag_cloud_args’ );
function wpe_widget_tag_cloud_args( $args ) {
$args[‘largest’] = 8;
$args[‘smallest’] = 12;
$args[‘unit’] = ‘px';
return $args;
}
[/php]

Excluding A Tag/Term From The Tag Cloud

Exclude key is comma separated term_id list to exclude. For example ‘exclude’ => 25,36 or $args[‘exclude’] = array(25, 36);. This means that tags with the term_id 25 or 36 will NOT be displayed on the widget.
[/php]
add_filter( ‘widget_tag_cloud_args’, ‘wpe_widget_tag_cloud_args’ );
function wpe_widget_tag_cloud_args( $args ) {
$args[‘exclude’] = array(25, 36);
return $args;
}
[php]

<h3>Including A Tag/Term From The Tag Cloud</h3>
Include key is exact opposite to the exclude key, same comma separated term_id list but this time to include in widget function results. For example ‘include’ => 18, 38, 40 or $args[‘include’] = array(18, 38, 40);. This means that tags with the term_id 18 or 38 or 40 will be the only displayed terms on the widget.
[php]
add_filter( ‘widget_tag_cloud_args’, ‘wpe_widget_tag_cloud_args’ );
function wpe_widget_tag_cloud_args( $args ) {
$args[‘include’] = array(25, 36);
return $args;
}
[/php]

Display only one category on home page

display only one category on home pageWell nowadays I found that there are many people looking for a plugin, snippet or hack to control displaying posts on the home page. This is snippet focused on displaying posts on the homepage from chosen category or categories.

So here is the snippet code or hack, now you just have to paste the code below in your functions.php file. Please be sure that you paste the code under the php tags.
 

 

 

PHP – Display only one category on home page

[php]
function my_category_queries( $query ) {
// only homepage and is the main query
if ($query->is_home() && $query->is_main_query()){
// display only posts in category with slug ‘articles’
$query->set(‘category_name’, ‘articles’);
// avoid sticky posts
$query->set(‘post__not_in’, get_option( ‘sticky_posts’ ) );
}
}<br />
add_action( ‘pre_get_posts’, ‘my_category_queries’ );

[/php]

Conclusion:
As you can see at the beginning of the function we are using the conditional functions is_home() witch is used for The Main Page and is_main_query() Is Main Query witch affect only to the main loop, and the function will proceed if both of conditions are true.
[php]$query->is_home() && $query->is_main_query()[/php]

The first $query-> ensures that all the posts are displayed with the category slug articles, this includes all Sticky Posts with any category, too.
[php]$query->set(‘category_name’, ‘articles’)[/php]

But then with the second $query-> set it to get all the posts with the category slug articles except for the posts that are sticky posts.
[php]$query->set(‘post__not_in’, get_option( ‘sticky_posts’ ) )[/php]

Additional notes:

Category Parameters
[php]
cat (int) – use category id.
category_name (string) – use category slug (NOT name).
category__and (array) – use category id.
category__in (array) – use category id.
category__not_in (array) – use category id.
[/php]

Let’s explain those parameters on our example now, well the first two commands works pretty same but the difference is that on first one we use Category ID’s and second one slugs. So basically if we wish to query the posts from two categories on the homepage we can simply update the code to ‘articles,affiliate-programs’ and function will call posts from the both categories on the homepage loop.

PHP – Display multiple categories on homepage

[php]
function my_category_queries( $query ) {
// only homepage and is the main query
if ($query->is_home() && $query->is_main_query()){
// display only posts in category with slug ‘articles’
// and slug ‘affiliate-programs’
$query->set(‘category_name’, ‘articles,affiliate-programs’);
// avoid sticky posts
$query->set(‘post__not_in’, get_option( ‘sticky_posts’ ) );
}
}

add_action( ‘pre_get_posts’, ‘my_category_queries’ );
[/php]

The example will be with the cat command instead of category_name will look like example bellow where the 25 and 36 are the category id’s.
[php]$query->set(‘cat’, ‘25,36’);[/php]