Creating page templates for specific post types – WortGepresst



STARTSEITE MULTIMEDIA WORTGEPRESST FAMILIENBANDE BOOKMARK PRIVACY


Creating page templates for specific post types

By default, a custom page template will be available to the “page” post type.
To create a page template to specific post types, add a line under the template name with the post types you would like the template to support.
Example:

1
2
3
4
5
6
<?php
/*
Template Name: Full-width layout
Template Post Type: post, page, event
*/
// Page code here...
Alert:This ability to add page templates to post types other than “page” post type is supported only from WordPress 4.7

When at least one template exists for a post type, the ‘Post Attributes’ meta box will be displayed in the back end, without the need to add post type support for ‘page-attributes’ or anything else. The ‘Post Attributes’ label can be customzied per post type using the ‘attributes’ label when registering a post type.
Backward Compatibility:
Let’s say you want to publicly release a theme with support for post type templates. WordPress versions before 4.7 will ignore the Template Post Type header and show the template in the list of page templates, even though it only works for regular posts. To prevent that, you can hook into the theme_page_templates filter to exclude it from the list. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Hides the custom post template for pages on WordPress 4.6 and older
*
* @param array $post_templates Array of page templates. Keys are filenames, values are translated names.
* @return array Filtered array of page templates.
*/
function makewp_exclude_page_templates( $post_templates ) {
if ( version_compare( $GLOBALS['wp_version'], '4.7', '&lt;' ) ) {
unset( $post_templates['templates/my-full-width-post-template.php'] );
}
return $post_templates;
}
add_filter( 'theme_page_templates', 'makewp_exclude_page_templates' );

That way you can support custom post type templates in WordPress 4.7 and beyond while maintaining full backward compatibility.
Note that theme_page_templates is actually a dynamic theme_{$post_type}_templates filter. The dynamic portion of the hook name, $post_type, refers to the post type supported by the templates. E.g. you can hook into theme_product_templates to filter the list of templates for the product post type.
Quelle: //developer.wordpress.org/themes/template-files-section/page-template-files/#creating-page-templates-for-specific-post-types

Font Resize
Contrast
Zur Werkzeugleiste springen