Hyphens instead of Underscores in Post-type Archive Template Filenames when Post-type handle contains underscore

I’m working on implementing WordPress coding standards on a theme which has several custom post-types, each of which have underscores in their handles.

The theme uses the custom post-type handle in the file-names, eg: archive-my_posttype.php for the my_posttype post-type… But WordPress coding standards require that filenames use hyphens and not underscores, ( see WordPress.Files.FileName.NotHyphenatedLowercase for more info )

I’ve changed the file-name of the archive-template to archive-my-posttype.php but I’m apprehensive because I remember this behavior didn’t exist previously.

example:

register_post_type( 'my_posttype' /* truncated for brevity */ ); 

Would correspond to the template-files archive-my_posttype.php & single-my_posttype.php but not archive-my-posttype.php & single-my-posttype.php

I recall being required to use the underscores in my filenames in the past. Can anyone tell me when this was changed and if it has anything to do with the rewrite-attribute being set when the CPT is registered?

I’m happy to see that I can replace the underscores with hyphens without issue, I’m just wondering when this became not an issue & if anyone knows any other conditions of this feature that people should be aware of

1 Answer
1

I was mistaken. The underscores are required by the template-files if they are part of the custom-post-type’s handle.

  1. Make sure to flush the rewrite cache / visit the permalinks page when working with cpt templates
  2. The archive.php template the missing cpt-template was falling back to looked similar
  3. Following wp-includes/template-loader.php >> get_post_type_archive_template >> get_archive_template doesn’t look like it’s rewriting underscores to hyphens

The characters used in the template filenames must match the cpt-handle exactly. WordPress coding standards require that filenames do not contain underscores.

We should (probably) avoid the use of underscores in cpt-handles.

Not sure if it’s WordPress or php/mysql version or settings related, but hyphens seem to be valid characters to use in post-type handles ( where I don’t recall them being previously )

eg: we couldn’t write register_post_type( 'my-posttype' ), but instead had to use register_post_type( 'my_posttype' )

So we could register post-types with hyphens in the handles to
punctuate namespace from the actual handle & by doing so we would have cpt-archive/single page template filenames that are WordPress coding standards compliant

Leave a Comment