Last active
January 5, 2019 21:03
-
-
Save jarcos/3a776a6f76286c39038ece47144f00d9 to your computer and use it in GitHub Desktop.
Add a WordPress Page Template from a Plugin from a functional programming point of view
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 | |
/** | |
* Inspiration: https://www.wpexplorer.com/wordpress-page-templates-plugin/ | |
*/ | |
add_filter( 'theme_page_templates', 'add_new_template' ); | |
add_filter( 'wp_insert_post_data', 'register_templates' ); | |
add_filter( 'template_include', 'view_template' ); | |
function register_templates( $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, 'themes' ); | |
$templates = array_merge( | |
$templates, | |
array( plugin_dir_url( __DIR__ ) . '/plugin-name/templates/template-name.php' => 'Template Name' ) | |
); | |
wp_cache_add( $cache_key, $templates, 'themes', 1800 ); | |
return $atts; | |
} | |
function view_template( $template ) { | |
$page_template = array( plugin_dir_url( __DIR__ ) . '/plugin-name/templates/template-name.php' => 'Template Name' ); | |
global $post; | |
if ( ! $post ) { | |
return $template; | |
} | |
if ( ! isset( | |
$page_template[ get_post_meta( | |
$post->ID, | |
'_wp_page_template', | |
true | |
) ] | |
) ) { | |
return $template; | |
} | |
$file = plugin_dir_path( __FILE__ ) . get_post_meta( | |
$post->ID, | |
'_wp_page_template', | |
true | |
); | |
if ( file_exists( $file ) ) { | |
return $file; | |
} else { | |
echo $file; | |
} | |
return $template; | |
} | |
function add_new_template( $posts_templates ) { | |
$posts_templates = array_merge( | |
$posts_templates, | |
array( plugin_dir_url( __DIR__ ) . '/plugin-name/templates/template-name.php' => 'Template Name' ) | |
); | |
return $posts_templates; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment