Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress plugin custom post type single page

Tags:

php

wordpress

I'm working on a Wordpress plugin that creates a custom post type. That custom post type will need it's own single.php page. I know that I can just create a file called single-{custom post type}.php in my theme, but I need this file to be in the plugin directory itself. How do I get Wordpress to recognize that I want to use the single-posttype.php from my plugin directory instead of my theme directory?

like image 781
Dominick Allen Avatar asked Aug 11 '26 06:08

Dominick Allen


1 Answers

Here's what I use, just replace dirname(__FILE__) .'/templates/ with whatever directory structure you have. The nice thing about this is it will default to the proper theme file if you don't have an "override" file at the $file location.

add_filter( 'single_template', 'override_single_template' );
function override_single_template( $single_template ){
    global $post;

    $file = dirname(__FILE__) .'/templates/single-'. $post->post_type .'.php';

    if( file_exists( $file ) ) $single_template = $file;

    return $single_template;
}

And of course your can do the same with with

archive_template

and

 $file = dirname(__FILE__) .'/templates/archive-'. $post->post_type .'.php';
like image 176
Xhynk Avatar answered Aug 13 '26 22:08

Xhynk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!