Introducing page templates (customized pages) in WordPress in the form of plug-ins
demand
realization
-
theme_page_templates
theme_page_templates It is the function hook called by WordPress when it gets the list of page templates. //Wild/rabbit @ catalpa/meow/come out/disappear (www.azimiao. com) apply_filters( 'theme_page_templates', array $page_templates, WP_Theme $this, WP_Post|null $post ) Among them, $page_templates This is the original page template list array. -
template_include
template_include It is a function hook called by WordPress when it obtains the path of the template file before including the template file. //Zimiao.com apply_filters( 'template_include', string $template ) Among them, $template This is the original page template file path.
//Define the template file path prefix, and use the plug-in root directory here define('ZM_PLUGIN_DIR', plugin_dir_path(__FILE__)); //List of external templates (Zimiao appearance blog | azimiao. com) to be imported $templates_new = array( "Page mycustom. php"=>"My presence 1" ); function zm_register_page(){ add_filter('theme_page_templates', 'zm_add_template'); add_filter('template_include', 'zm_view_template'); } function zm_add_template( $posts_templates ) { global $templates_new; $posts_templates = array_merge( $posts_templates,$templates_new ); return $posts_templates; } function zm_view_template( $template ) { global $post; global $templates_new; if ( !isset( $post ) ) return $template; //Get the page (Zimiao haunt blog | azimiao. com) template name $t_template_name = get_post_meta( $post->ID, '_wp_page_template', true ); //The page template is not in the custom list. Return directly if ( ! isset( $templates_new[ $t_template_name ] ) ) { return $template; } //The correct path of splicing template (Zimiao haunting blog | azimiao. com) //Assume that the template is stored in the plug-in directory/custompage/ $file = ZM_PLUGIN_DIR . ' custompage/' . $ t_template_name; //(Zimiao haunts blog | azimiao. com) if( file_exists( $file ) ) { return $file; } return $template; }
add_action( "plugins_loaded", "zm_register_page");
verification