3

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

4

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:

2
  • Looks like you beat be to it, I didn't notice your answer until I posted mine ;-) I will delete mine +1
    – birgire
    Commented Jul 3, 2015 at 12:35
  • @birgire It might be worth leaving it as I didn't go so far as to create the function.
    – Jami Gibbs
    Commented Jul 3, 2015 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.