Your previous question, Possible to create a "variant" page template that only contains differences and is therefore resilient to updates of original (ie page.php)?, provided nicely more context to this question.
As you Sally CJ noted in the comments you use theme_page_templates to add custom template to the template select list. To skip adding a separate file for the template, use template_include filter to select page.php
as the actual template file. Target the template on the front end on template_redirect action with is_page_template() conditional to add data printing function to wp_head
.
For example like this,
function my_service_template_slug() {
return 'my-service-template.php';
}
function my_service_template_name() {
return __( 'My Service Template', 'my-textdomain' );
}
// Add custom template to the template list
add_filter(
'theme_page_templates',
function( $page_templates, $theme, $post ){
$page_templates[my_service_template_slug()] = my_service_template_name();
return $page_templates;
},
11,
3
);
// Use default page.php as servcie template
add_filter(
'template_include',
function( $template ) {
return my_service_template_slug() === $template ? 'page.php' : $template;
},
11,
1
);
// Add data to service template head
add_action(
'template_redirect',
function(){
if ( is_page_template( my_service_template_slug() ) ) {
add_action( 'wp_head', 'my_service_template_head_data');
}
}
);
function my_service_template_head_data() {
// print something
}
theme_page_templates
hook, but I posted this as a comment because I don't get the "I really don't want a whole new servicepage.php file". Or that the hook I mentioned requires a template file.include
page.php, as mentioned here: wordpress.org/support/topic/… but still interested to do it with a file-less solution if one presents itself that I can manage. =)