Dynamic page templates in WordPress 4.4
Published January 20th, 2016 under General
WordPress 4.4 added an improved system for dynamically adding page templates via plugins.
To make this simple for you to implement yourselves, I’ve created this short example class which adds a simple page template which dumps extra text into the content area. There is no physical page template file, the page templates can be totally virtual with this new system.
The filter you need to use is callled theme_page_templates
. With this you can simply add any page templates into the returned array as shown. Then to display this template, you just need to hook into the template_redirect
action hook and do a check for the required page template and modify the output to suit. In this example I simply added a filter to the_content
, but you could also totally rewrite the template here if you wanted to.
<?php /** * Adding a dynamic page template. * * @copyright Copyright (c), Ryan Hellyer * @author Ryan Hellyer <ryanhellyergmail.com> * @since 1.0 */ class Adding_A_Page_Template { /** * Set template file constant. */ const TEMPLATE_FILE = 'some-template.php'; /** * Fire the constructor up :) */ public function __construct() { add_filter( 'theme_page_templates', array( $this, 'add_page_templates' ) ); add_action( 'template_redirect', array( $this, 'use_page_template' ) ); } /** * Add page templates. * * @param array $templates The list of page templates * @return array $templates The modified list of page templates */ public function add_page_templates( $templates ) { $templates[self::TEMPLATE_FILE] = __( 'Some template name', 'plugin-slug' ); return $templates; } /** * Modify page content if using a specific page template. */ public function use_page_template() { $page_template = get_post_meta( get_the_ID(), '_wp_page_template', true ); if ( self::TEMPLATE_FILE == $page_template ) { add_filter( 'the_content', array( $this, 'content_filter' ) ); } } /** * Add special content to the top of the content area. * * @param string $content The page content * @return string $content The modified page content */ public function content_filter( $content ) { $content = '<p><strong>' . __( 'This page template has extra stuff at the top of each content section!', 'plugin-slug' ) . '</strong></p>' . $content; return $content; } } new Adding_A_Page_Template();
RT Cunningham says:
I think I’m confused. The line with
const TEMPLATE_FILE = 'some-template.php';
seems to imply a physical template.February 7, 2016 at 9:26 am # //
Ryan says:
It’s definitely not a physical file though. It’s just an arbitrary label.
Sorry for not responding sooner. The notification of your comment must have gotten lost in my inbox somewhere.
February 24, 2016 at 9:18 am # //