darkhorse
darkhorse

Reputation: 8772

Custom page template from plugin does not work with pre-installed themes in WordPress 2024

So I have a simple Wordpress plugin that just allows me to use custom page templates. Here's the code:

my-special-template.php

<?php
/**
 * Plugin Name: My Special Template
 * Description: Awesome description.
 **/

function my_template_array()
{
    $temps = [];

    $temps['john.php'] = 'John';
    $temps['jack.php'] = 'Jack';

    return $temps;
}

function my_template_register($page_templates,$theme,$post)
{
    $templates = my_template_array();

    foreach ($templates as $tk => $tv)
    {
        $page_templates[$tk] = $tv; 
    }

    return $page_templates;
}
add_filter('theme_page_templates','my_template_register',10,3);

function my_template_select($template)
{
    global $post, $wp_query, $wpdb;

    if (isset($post->ID))
    {
        $page_temp_slug = get_page_template_slug($post->ID);

        $templates = my_template_array();

        if (isset($templates[$page_temp_slug]))
        {
            $template = plugin_dir_path(__FILE__).'templates/'.$page_temp_slug;
        }
    }

    //echo '<pre>Preformatted:';print_r($page_temp_slug);echo '</pre>';

    return $template;
}
add_filter('template_include', 'my_template_select', 99)

?>

And the templates:

<?php
/* Template Name: Jack */
?>
Jack
<?php
/* Template Name: John */
?>
John

When I use a theme like Hello Elementor, or Simple Persona, the custom templates can be selected from the template dropdown and the plugin works perfectly:

enter image description here

However, if I used a theme like Twenty Twenty Four that comes pre-installed with WordPress, then I get this:

enter image description here

I can't actually select my plugin templates. What gives? How can I fix this? My WordPress is 6.6.1, or the latest one at this moment.

Upvotes: 1

Views: 92

Answers (1)

Narendra Sishodiya
Narendra Sishodiya

Reputation: 603

I have checked this and found that this plugin is not working for Twenty Twenty Four because Twenty Twenty Four is the block theme and for this there is a different mechanism to add templates.

You can add .html templates to templates folder of the theme and then you need to register these in customTemplates object of theme.json file.

You requirement will be addressed in the upcoming version of WordPress 6.7 there is also detailed post regarding the same.

Upvotes: 1

Related Questions