Skip to content

Commit

Permalink
Add post format support for single post templates.
Browse files Browse the repository at this point in the history
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
  • Loading branch information
justintadlock committed Jul 11, 2024
1 parent 3829923 commit f47d134
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/Templates.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ public function registerTypes(array $types): array
];

foreach (get_post_format_strings() as $format => $label) {
$types["single-post-format-{$format}"] ??= [
'title' => sprintf(_x('Single Post: %s', 'Template name', 'x3p0-ideas'), $label),
'description' => sprintf(__('Displays single %s posts on your website unless a custom template has been applied to that post.', 'x3p0-ideas'), $label)
];

$types["taxonomy-post_format-post-format-{$format}"] ??= [
'title' => sprintf(_x('Post Format Archive: %s', 'Template Name', 'x3p0-ideas'), $label),
'description' => sprintf(__('Displays an archive of %s posts.', 'x3p0-ideas'), $label)
Expand All @@ -112,4 +117,44 @@ public function registerTypes(array $types): array

return $types;
}

/**
* Adds post format support for single post templates.
*
* @hook single_template_hierarchy last
* @since 1.0.0
*/
public function singleTemplateHierarchy(array $templates): array
{
$post = get_queried_object();

if (! post_type_supports($post->post_type, 'post-formats')) {
return $templates;
}

$templates = [];
$custom = get_page_template_slug($post);
$name_decoded = urldecode($post->post_name);
$post_format = get_post_format($post);

if ($custom && 0 === validate_file($custom)) {
$templates[] = $custom;
}

if ( $name_decoded !== $post->post_name ) {
$templates[] = "single-{$post->post_type}-{$name_decoded}.php";
}

$templates[] = "single-{$post->post_type}-{$post->post_name}.php";

// @todo - Do we want to allow for format templates based on type?
if ($post_format) {
$templates[] = "single-post-format-{$post_format}.php";
}

$templates[] = "single-{$post->post_type}.php";
$templates[] = 'single.php';

return $templates;
}
}

0 comments on commit f47d134

Please sign in to comment.