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?

3

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:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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