I created a plugin and added a custom post type to the plugin. I then created a template using the hierarchy single-{custom-post-type}.php
. So my cpt slug is wppro-events
and the single post template is called single-wppro-events.php
. I also added to the top of the template file the comment section below but my post template is not being used for the cpt. Any idea why it is not being used. Also page attributes on the edit page isn't showing the option to change the template either. Astra is the theme I am using. Any idea why this isn't working?
/*
Template Name: Layout One
Template Post Type: wppro-events
*/
I also tried the below code but still didn't work:
/* Filter the single_template with our custom function*/
add_filter('single_template', 'my_custom_template');
function my_custom_template($single) {
global $post;
/* Checks for single template by post type */
if ( $post->post_type == 'Event Items' ) {
if ( file_exists( PLUGIN_PATH . '/single-wppro-events.php' ) ) {
return PLUGIN_PATH . '/single-wppro-events.php';
}
}
return $single;
}
Additional Information Requested
Register CPT code
function wppro_register_events_post_type() {
$labels = array(
'name' => __( 'Events', 'wppro' ),
'singular_name' => __( 'Event', 'wppro' ),
'add_new' => __( 'Add New Event', 'wppro' ),
'add_new_item' => __( 'Add New Event', 'wppro' ),
'edit_item' => __( 'Edit Event', 'wppro' ),
'new_item' => __( 'New Event', 'wppro' ),
'view_item' => __( 'View Event', 'wppro' ),
'search_items' => __( 'Search Events', 'wppro' ),
'not_found' => __( 'No events found', 'wppro' ),
'not_found_in_trash' => __( 'No events found in trash', 'wppro' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'wppro-events' ),
'menu_position' => 20,
'menu_icon' => 'dashicons-calendar',
'supports' => array( 'title', 'editor', 'thumbnail' ),
);
register_post_type( 'wppro-events', $args );
}
add_action( 'init', 'wppro_register_events_post_type' );
The plugin is a standalone one in wp-contents/plugins
. I put the template file in the plugin's root directory.
wp-content/plugins
) or is it part of your theme? Is it a block-based or classic theme? Where did you put your template file - in the root theme folder, e.g.wp-content/themes/your-theme
? Can you add all that details, along with your post type registration code, to your question?PLUGIN_PATH
set to? (I assume it's the root directory of your plugin.) Also: the Template Hierarchy's auto-selection of template files only works for files in your active theme. To load a template file located in your plugin, you'll need to use a filter. Ifsingle_template
isn't working, perhapssingular_template
or the more generictemplate_include
might do it.if ( $post->post_type == 'wppro-events' )
, and your custom template would then be used for single post pages in your CPT. So I was just wondering, have you tried that and did it work? If yes, then is there something else you wanted to know?