Created
April 29, 2021 11:26
-
-
Save lasida/757b5b4bd41c7d78cf27e21aafe3dcfe to your computer and use it in GitHub Desktop.
Create Template Page WordPress
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
Class TemplatePage | |
{ | |
public function __construct() | |
{ | |
$this->templates = array(); | |
if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.7', '<' ) ) { | |
add_filter('page_attributes_dropdown_pages_args',array( $this, 'register' )); | |
} else { | |
add_filter('theme_page_templates', array( $this, 'create' )); | |
} | |
add_filter('wp_insert_post_data',array( $this, 'register' )); | |
add_filter('template_include',array( $this, 'view')); | |
$this->templates = array( | |
// 'main.php' => __( 'LSDDonation - Main', 'lsddonation' ), | |
'payment.php' => __( 'LSDDonation - Payment', 'lsddonation' ), | |
); | |
} | |
public function create( $posts_templates ) | |
{ | |
$posts_templates = array_merge( $posts_templates, $this->templates ); | |
return $posts_templates; | |
} | |
public function register( $atts ) { | |
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() ); | |
$templates = wp_get_theme()->get_page_templates(); | |
if ( empty( $templates ) ) { | |
$templates = array(); | |
} | |
wp_cache_delete( $cache_key , 'lsddonation'); | |
$templates = array_merge( $templates, $this->templates ); | |
wp_cache_add( $cache_key, $templates, 'lsddonation', 1800 ); | |
return $atts; | |
} | |
public function view( $template ) { | |
if ( is_search() ) { | |
return $template; | |
} | |
global $post; | |
if ( ! $post ) { | |
return $template; | |
} | |
if ( ! isset( $this->templates[get_post_meta( | |
$post->ID, '_wp_page_template', true | |
)] ) ) { | |
return $template; | |
} | |
// Allows filtering of file path | |
$filepath = apply_filters( 'page_templater_plugin_dir_path', plugin_dir_path( __FILE__ ) ); | |
$file = LSDD_PATH . 'public/templates/' . get_post_meta( | |
$post->ID, '_wp_page_template', true | |
); | |
// Just to be safe, we check if the file exist first | |
if ( file_exists( $file ) ) { | |
return $file; | |
} else { | |
echo $file; | |
} | |
return $template; | |
} | |
} | |
new TemplatePage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment