Custom Post Type – Template
-
So I am currently working with a client that wishes to use the latest and greatest of WP. One of the features that they required was ‘custom post types’. After doing a little research I found that WP does not automatically point custom post type single post views to a template other than single.php, by default.
So I began to search for other solutions that people had come up with to solve this problem. Every single solution I found, hooked the ‘template_redirect’ action to point to the new template file and basically just died after including it. An example can be found on this page, but I have pasted it here for clarity:
add_action('template_redirect', 'my_template_redirect'); // Template selection function my_template_redirect() { global $wp; global $wp_query; if ($wp->query_vars['post_type'] == 'property') { // Let's look for the property.php template file in the current theme if (have_posts()) { include(TEMPLATEPATH . '/property.php'); die(); } else { $wp_query->is_404 = true; } } }
So this does in fact ‘solve the problem’, so to speak, but how well does it? The problem with this snippet is that it does not allow WP to do it’s clean up, such as: close DB connections, destroy objects, ect…
There is a better solution, and it is built in. Observe the following:
function bmrw_template_include($incFile) { global $wp; global $wp_query; if ($wp->query_vars['post_type'] == 'my_custom_post_type') { if (have_posts()) { $file = TEMPLATEPATH.'/my_custom_post_type.php'; if (file_exists($file)) { $incFile = $file; } else { $wp_query->is_404 = true; } } else { $wp_query->is_404 = true; } } return $incFile; } add_filter('template_include', 'bmrw_template_include');
Now this solution allows the WP core scripts to continue execution, completing any clean-up that needs to take place. It already has a hook that you can use, you don’t have to modify the base WP code, and it does not kill the execution of the WP core code. Problem solved.
- The topic ‘Custom Post Type – Template’ is closed to new replies.