Site logo

Archived topic

Getting GPP to load CPT templates from a plugin rather than child theme

4 replies · Started by feisar on May 5, 2021

Viewing posts 1–5 of 5

I've made a simple WP plugin that creates a Custom Post Type specifically for use with my GPP-based websites.

At the moment I'm using the single-{cpt-name}.php, archive-{cpt-name}.php and content-{cpt-name}.php templates in my child theme to output the custom post type and custom fields data, which works fine.

This, however, requires that the template files are manually added into the child theme independently of installing the plugin.

What is the recommended "GPP" way of doing this so that GeneratePress looks in the plugin folder for the template files rather than in the child theme folder? My aim is to get everything working from the plugin without having to install files in the child theme. Are there GPP Hooks that would help?

I've tried some code from StackExchange but I can't get it to work, so I'm not sure whether that code works with GeneratePress. Does it look like it should?

Thank you.

I didn't get a reply to my post above for some reason, but have since used the following code, which seems to work ok. I'd still be interested to hear if this is the best way for GPP child themes, or if there are other hooks/filters I should be using.

add_filter( 'single_template', 'cpt_single_template' );
function cpt_single_template( $template ) {
    global $post;
    /* if no single events template in theme folder, load from plugin folder */
    if ( 'events' === $post->post_type && locate_template( [ 'single-events.php' ] ) !== $template ) {
        if ( file_exists( plugin_dir_path( __FILE__ ) . 'templates/single-events.php' ) ) {
            return plugin_dir_path( __FILE__ ) . 'templates/single-events.php';
        }
    }

    return $template;
}

add_filter( 'archive_template', 'cpt_archive_template' );
function cpt_archive_template( $template ) {
    global $post;
    /* if no archive events template in theme folder, load from plugin folder */
    if ( 'events' === $post->post_type && locate_template( [ 'archive-events.php' ] ) !== $template ) {
        if ( file_exists( plugin_dir_path( __FILE__ ) . 'templates/archive-events.php' ) ) {
            return plugin_dir_path( __FILE__ ) . 'templates/archive-events.php';
        }
    }

    return $template;
}

Thanks.

Hi there,

it seems your original topic slipped past our system - please accept our apologies for this.

The method you used ie.{$type}_template filter is the logical way of doing it.

No worries - it pushed me to experiment more!

Thanks for confirming the {$type}_template filter is way to do it.

Thanks for understanding - and thanks for sharing your solution!

This archived topic is closed to new replies.