Limit number of pages that use a specific template?

I have a custom page template, so a .php file in my themes folder with this at the beginning

/*
 * Template Name: MyTemplate
 */

Now I can, in the WP backend, create new pages and select this template so that the page created uses this template.

How can I limit the number of pages using this template? For example, if I only want to allow one single page using this template? Or if there’s only ever allowed three pages that may use it. How can I achieve this?

1 Answer
1

You can approach this by first using a database query to count the number of pages that are already using the template:

$query = "SELECT COUNT(*) as total
    FROM prefix_posts as p JOIN prefix_postmeta as m ON p.ID = m.post_id
    WHERE p.'post_type' = 'page'
    AND p.'post_status' = 'publish'
    AND m.'meta_key'    = '_wp_page_template'
    AND m.'meta_value'  = 'page-your-template-name.php'";

Then check if your count limit has been reached and remove the page template with the theme_page_templates filter:

Leave a Comment