• I have a CPT and would like to set a custom template file as default.

    Right now it always used the “Single Posts” template. I could add a template with single-{cpt}.html but that’s not an option for me as I have no control of the used them.

    • This topic was modified 6 months, 1 week ago by Xaver.
Viewing 2 replies - 1 through 2 (of 2 total)
  • 1. Create the Custom Template File:

    First, create a template file that you want to use as the default template for your custom post type. For example, create a file called single-work.php (assuming your custom post type is work).

    You can store this file within your plugin’s directory, for example: /my-plugin/templates/single-work.php.

    2. Use the template_include Filter to Override the Template:

    In your plugin, use the template_include filter to specify the custom template for your custom post type.

    function my_plugin_custom_post_type_template( $template ) {
    if ( is_singular( 'work' ) ) {
    // Define the path to the template file inside your plugin
    $plugin_template = plugin_dir_path( __FILE__ ) . 'templates/single-work.php';

    // Check if the template file exists
    if ( file_exists( $plugin_template ) ) {
    return $plugin_template;
    }
    }
    return $template;
    }
    add_filter( 'template_include', 'my_plugin_custom_post_type_template' );

    Example structure of single-work.php:
    Make sure that your custom template file (single-work.php) follows WordPress’ template structure, including get_header(), get_footer(), etc

    <?php get_header(); ?>

    <div id="primary" class="content-area">
    <main id="main" class="site-main">
    <?php
    while ( have_posts() ) :
    the_post();
    // Custom template content for 'work' post type
    the_title( '<h1>', '</h1>' );
    the_content();
    endwhile;
    ?>
    </main>
    </div>

    <?php get_footer(); ?>
    Thread Starter Xaver

    (@xaverb)

    Thanks @mayuripatel!

    I was searching for a way to do this for block themes, not classic themes. This should also be reflected on the backend as well.

    Thank you anyway!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to set default template for custom post type from a plugin.’ is closed to new replies.