I have registered a Custom Post Type and created a file called archive-myCPT.php and another one for single posts called single-myCPT.php.
What I want to do is to create a page where I will show just few posts from my Custom Post Type. Inside my archive-myCPT.php I will have a link called let’s say “Special Posts” and this link will go to the custom page which will be a little bit different from archive-myCPT.php, the only difference is that here I will use a custom query for the posts.
The only way to do this seems to create a page template, but the problem here is that I can not assign a page template to pages within my CPT. I found this plugin which may help me with the page template support for my Custom Post Type, but is pretty old and I don’t know if it’s compatible with the latest version of WordPress.
Is there any other way to achieve this?
Is this a common / good practice?
Maybe you could recommend something else?
If you’re adding a custom query within the template to load posts, the post type of that page doesn’t have to be your custom post type. You can create a plain vanilla
page
, create a template for that viapage-your_page_slug.php
, or via a custom template assigned in the templates dropdown, then query for whatever post type you want viaWP_Query
.EDIT – here’s an example using the
single_template
filter. you’ll have to change the post type and slug to match yours.adapted from the example on Template Hierarchy: Filter Hierarchy.
You would think that it would be as simple as adding
add_post_type_support( 'cptslug', 'page-attributes' );
to your code, but it isn’t. If you check the source you will see that the template dropdown is restricted to thepage
post type only. There is also a note in the Codex and a reference to a closed Trac ticket on the topic.You can add that box to your CPT by copying the Core function, making a small edit and adding a new box.
If you test that code, you will notice that the box appears but the data doesn’t save. Here is why.
We are going to have to save the data ourselves.
Now it should save but the template doesn’t load. Here is why.
get_single_template
runs beforeget_page_template
, andget_page_template
is what looks for the specialized templates. So we need to load that template ourselves.Barely tested. Possibly buggy. Caveat emptor. No refunds.