Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Custom post type display for plugin WordPress

  • SOLVED

How can I define a custom post type's display template from within a plugin? I know how the WP template hierarchy works but am looking for a solution that defines the content via the plugin folder and not the theme directory.

To explain it differently I haven't been able to find an automated way of overriding the post template when it displays a product besides having the single product template function called within a theme template.


Example: Plugin "wpsellme" registers a CPT called "Product". A single Product page needs to display a custom taxonomy also created by wpsellme. The template must reside in the /plugins/wpsellme directory.


There is a $15 optional bonus for integration with our current code.

Thanks!

Answers (2)

2010-11-03

rilwis answers:

Try this:

add_action('template_redirect', 'my_template', 5);

function my_template() {
$post_type = get_query_var('post_type'));
if ($post_type == 'product') { // check your post type
load_template(WP_PLUGIN_DIR . '/your_plugin_name' . '/product.php');
exit;
}
}


Michael is right that we can fit a template file to all themes. But I think you have your own reason :)


rilwis comments:

We can enhance the script to check for template file before using our own file (inside plugin folder). This way we can make sure website runs even users forget to create the template for custom post type:

add_action('template_redirect', 'my_template', 5);

function my_template() {
$post_type = get_query_var('post_type'));
if ($post_type == 'product') { // check your post type
if (file_exists(TEMPLATEPATH . '/single-' . $post_type . '.php')) return;
load_template(WP_PLUGIN_DIR . '/your_plugin_name' . '/product.php');
exit;
}
}

2010-11-03

Michael Fields answers:

You need to hook into the template_redirect hook. Be sure to use exit() to terminate script execution after you have included the appropriate file.

That being said, I would highly recommend that you <strong>DO NOT</strong> do this. It is absolutely impossible to match every theme's html structure using a single template. You can read more here: http://www.leewillis.co.uk/wordpress-custom-post-type-theming-is-broken/