One Template for All Custom Post Types
Lets every custom post type use a shared archive-custom and single-custom template before falling back to the general ones, so you design CPT pages once.
Opens WPIDE on
Code
add_filter( 'archive_template_hierarchy', function ( $templates ) {
if ( ! is_post_type_archive() || is_post_type_archive( 'post' ) ) {
return $templates;
}
$pos = array_search( 'archive.php', $templates, true );
array_splice( $templates, false === $pos ? count( $templates ) : $pos, 0, array( 'archive-custom.php' ) );
return $templates;
} );
add_filter( 'single_template_hierarchy', function ( $templates ) {
$type = get_post_type( get_queried_object_id() );
if ( ! $type || in_array( $type, array( 'post', 'attachment' ), true ) || get_post_type_object( $type )->_builtin ) {
return $templates;
}
$pos = array_search( 'single.php', $templates, true );
array_splice( $templates, false === $pos ? count( $templates ) : $pos, 0, array( 'single-custom.php' ) );
return $templates;
} );
Notes
Create archive-custom.php and single-custom.php in a classic theme, or templates named archive-custom and single-custom in a block theme. Post-type-specific templates still win.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.