Question

I want to create a new selectable page template for users that will allow them to identify which pages on the site are "Service" pages (eg plumbing, gas fitting, etc). The template is an exact copy of page.php but includes some JSON LD (schema.org code) for "Service" pages on their website.

I really don't want a whole new servicepage.php file for this, that is just a carbon copy of page.php.

(How) Could I do this using only functions.php? Adding a new plugin is not currently an option.

Was it helpful?

Solution

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top