-
-
Save PierreLebedel/4a845242ee787d33b9807bf99574a456 to your computer and use it in GitHub Desktop.
WordPress: add page template from custom plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Page templates from plugin | |
* Plugin URI: | |
* Description: Page templates from plugin | |
* Version: 1.0.0 | |
* Author: Pierre Lebedel | |
* Author URI: https://www.pierrelebedel.fr | |
*/ | |
class PageTemplatesFromPlugin { | |
private static $instance; | |
public $dirpath; | |
public $templatespath; | |
public $templates; | |
public static function getInstance() | |
{ | |
if( is_null(self::$instance) ){ | |
self::$instance = new PageTemplatesFromPlugin(); | |
} | |
return self::$instance; | |
} | |
private function __construct() | |
{ | |
$this->dirpath = plugin_dir_path(__FILE__); | |
$this->templatespath = $this->dirpath.'templates/'; | |
$this->templates = array( | |
'new-page-template.php' => "New template 1", | |
'new-page-template-bis.php' => "New template 2", | |
); | |
add_filter('theme_page_templates', array($this, 'mergeTemplates')); | |
add_filter('save_post_page', array($this, 'savePostPage'), 10, 3); | |
add_filter('template_include', array($this, 'useTemplate')); | |
} | |
public function mergeTemplates($posts_templates=array()) | |
{ | |
$posts_templates = array_merge($posts_templates, $this->templates); | |
return $posts_templates; | |
} | |
public function savePostPage($post_id, $post, $update) | |
{ | |
if( array_key_exists($post->page_template, $this->templates) ){ | |
update_post_meta($post->ID, '_wp_page_template', $post->page_template); | |
} | |
} | |
public function useTemplate($template) | |
{ | |
global $post; | |
if( !$post ){ | |
return $template; | |
} | |
$post_page_template = get_post_meta($post->ID, '_wp_page_template', true); | |
if( !array_key_exists($post_page_template, $this->templates) ){ | |
return $template; | |
} | |
if(file_exists($this->templatespath.$post_page_template)){ | |
return $this->templatespath.$post_page_template; | |
} | |
return $template; | |
} | |
} | |
add_action('plugins_loaded', array('PageTemplatesFromPlugin', 'getInstance') ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment