Skip to content

Commit f47d134

Browse files
committed
Add post format support for single post templates.
This filters `single_template_hierarchy` to add single post format support in the form of `single-post-format-{$format}`. It also registers these templates in the UI via the `default_template_types` filter hook. See: #17
1 parent 3829923 commit f47d134

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/Templates.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,11 @@ public function registerTypes(array $types): array
9999
];
100100

101101
foreach (get_post_format_strings() as $format => $label) {
102+
$types["single-post-format-{$format}"] ??= [
103+
'title' => sprintf(_x('Single Post: %s', 'Template name', 'x3p0-ideas'), $label),
104+
'description' => sprintf(__('Displays single %s posts on your website unless a custom template has been applied to that post.', 'x3p0-ideas'), $label)
105+
];
106+
102107
$types["taxonomy-post_format-post-format-{$format}"] ??= [
103108
'title' => sprintf(_x('Post Format Archive: %s', 'Template Name', 'x3p0-ideas'), $label),
104109
'description' => sprintf(__('Displays an archive of %s posts.', 'x3p0-ideas'), $label)
@@ -112,4 +117,44 @@ public function registerTypes(array $types): array
112117

113118
return $types;
114119
}
120+
121+
/**
122+
* Adds post format support for single post templates.
123+
*
124+
* @hook single_template_hierarchy last
125+
* @since 1.0.0
126+
*/
127+
public function singleTemplateHierarchy(array $templates): array
128+
{
129+
$post = get_queried_object();
130+
131+
if (! post_type_supports($post->post_type, 'post-formats')) {
132+
return $templates;
133+
}
134+
135+
$templates = [];
136+
$custom = get_page_template_slug($post);
137+
$name_decoded = urldecode($post->post_name);
138+
$post_format = get_post_format($post);
139+
140+
if ($custom && 0 === validate_file($custom)) {
141+
$templates[] = $custom;
142+
}
143+
144+
if ( $name_decoded !== $post->post_name ) {
145+
$templates[] = "single-{$post->post_type}-{$name_decoded}.php";
146+
}
147+
148+
$templates[] = "single-{$post->post_type}-{$post->post_name}.php";
149+
150+
// @todo - Do we want to allow for format templates based on type?
151+
if ($post_format) {
152+
$templates[] = "single-post-format-{$post_format}.php";
153+
}
154+
155+
$templates[] = "single-{$post->post_type}.php";
156+
$templates[] = 'single.php';
157+
158+
return $templates;
159+
}
115160
}

0 commit comments

Comments
 (0)