¿Crear plantillas de página personalizadas con complementos?
4 respuestas
- votos
-
- 2010-11-02
get_page_template()
sepuede anularmedianteelfiltropage_template
. Si su complementoes un directorio con lasplantillas como archivos,soloes cuestión depasar losnombres deestos archivos. Si desea crearlos "sobre lamarcha" (¿editarlosen el área de administración yguardarlosen labase de datos?),Esposible que deseeescribirlosen un directorio de caché y consultarlos,oengancharlosentemplate_redirect
y haz uneval()
cosas.Unejemplo simple de un complemento que "redirige" a un archivoen elmismo directorio de complementos si cierto criterioes verdadero:
add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'my-custom-page-slug' ) ) { $page_template = dirname( __FILE__ ) . '/custom-page-template.php'; } return $page_template; }
get_page_template()
can be overridden via thepage_template
filter. If your plugin is a directory with the templates as files in them, it's just a matter of passing the names of these files. If you want to create them "on the fly" (edit them in the admin area and save them in the database?), you might want to write them to a cache directory and refer to them, or hook intotemplate_redirect
and do some crazyeval()
stuff.A simple example for a plugin that "redirects" to a file in the same plugin directory if a certain criterium is true:
add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'my-custom-page-slug' ) ) { $page_template = dirname( __FILE__ ) . '/custom-page-template.php'; } return $page_template; }
-
Hola Jan,¿tienes algún código deejemplo sobre cómopasar un archivo de complemento como unaplantilla depáginapersonalizada?Hey Jan, do you have some example code on how to pass a plugin file in as a custom page template?
- 0
- 2010-11-16
- jnthnclrk
-
@trnsfrmr: Es realmentefácil,agregué unejemplo simple ami respuesta.@trnsfrmr: It's really easy, I added a simple example to my answer.
- 0
- 2010-11-16
- Jan Fabry
-
Tengaen cuenta queesto ha sidomás omenos reemplazadoporelfiltro "template_include"en versionesposteriores (3.1+).Note that this has been more or less replaced by the "template_include" filter in later versions (3.1+).
- 12
- 2013-06-10
- Inigoesdr
-
Perfecto !!!,me has ahorradoeltiempo @JanFabryPerfect !!!, you have save my time @JanFabry
- 0
- 2018-12-21
- Kishan Chauhan
-
Como dijo @fireydude,estanoes una solucióngenérica.Es una solución que codifica deforma rígidael slug de lapágina.As stated by @fireydude, this is not a generic solution. It's a workaround that hard-codes the page slug.
- 0
- 2019-07-07
- Mauro Colella
-
- 2015-10-12
Anular
get_page_template()
es solo untruco rápido. Nopermite seleccionar laplantilla desde lapantalla de administración y labarra depáginaestá codificadaen el complemento,por lo queel usuarionotiene forma de saber de dóndeproviene laplantilla.La soluciónpreferida sería seguir estetutorial que lepermite registrar unaplantilla depáginaen elback-end desdeel complemento. Entoncesfunciona como cualquier otraplantilla.
/* * Initializes the plugin by setting filters and administration functions. */ private function __construct() { $this->templates = array(); // Add a filter to the attributes metabox to inject template into the cache. add_filter('page_attributes_dropdown_pages_args', array( $this, 'register_project_templates' ) ); // Add a filter to the save post to inject out template into the page cache add_filter('wp_insert_post_data', array( $this, 'register_project_templates' ) ); // Add a filter to the template include to determine if the page has our // template assigned and return it's path add_filter('template_include', array( $this, 'view_project_template') ); // Add your templates to this array. $this->templates = array( 'goodtobebad-template.php' => 'It\'s Good to Be Bad', ); }
Overriding
get_page_template()
is just a quick hack. It does not allow the template to be selected from the Admin screen and the page slug is hard-coded into the plugin so the user has no way to know where the template is coming from.The preferred solution would be to follow this tutorial which allows you to register a page template in the back-end from the plug-in. Then it works like any other template.
/* * Initializes the plugin by setting filters and administration functions. */ private function __construct() { $this->templates = array(); // Add a filter to the attributes metabox to inject template into the cache. add_filter('page_attributes_dropdown_pages_args', array( $this, 'register_project_templates' ) ); // Add a filter to the save post to inject out template into the page cache add_filter('wp_insert_post_data', array( $this, 'register_project_templates' ) ); // Add a filter to the template include to determine if the page has our // template assigned and return it's path add_filter('template_include', array( $this, 'view_project_template') ); // Add your templates to this array. $this->templates = array( 'goodtobebad-template.php' => 'It\'s Good to Be Bad', ); }
-
Seríabueno (* ypreferido *) sipuedepublicarel código relevante delenlaceen su respuesta,de lo contrario,estonoesmás que un comentarioinflado :-)Would be nice (*and prefered*) if you can post the relevant code from the link in your answer, otherwise this is nothing more than a bloated comment :-)
- 0
- 2015-10-12
- Pieter Goosen
-
Eltutorial realmente acredita [elejemplo de Tom McFarlin] (https://github.com/tommcfarlin/page-template-example) comoel creador deesteenfoque.The tutorial actually credits [Tom McFarlin's example](https://github.com/tommcfarlin/page-template-example) as the originator of this approach.
- 1
- 2015-10-12
- fireydude
-
- 2014-12-04
Sí,esposible.Encontréeste complemento deejemplo muy útil.
Otroenfoque que seme viene a la cabezaes usar API de WP Filesystem para crearel archivo deplantilla altema.Noestoy seguro de que seaelmejorenfoque atomar,¡peroestoy seguro de quefunciona!
Yes, it is possible. I found this example plugin very helpful.
Another approach that is come into my head is using WP Filesystem API to create the template file to theme. I am not sure that it is the best approach to take, but I am sure it work!
-
El complemento deejemplo vinculadoestábastantebien documentado.Megustaeso.:)The linked example plugin is even pretty well documented. I like that. :)
- 0
- 2017-08-14
- Arvid
-
- 2019-10-22
Ninguna de las respuestas anterioresme funcionó. Aquí uno dondepuedeelegir suplantillaen la administración de Wordpress. Simplemente colóqueloen su archivoprincipal de complementophp y cambie
template-configurator.php
porelnombre de suplantilla//Load template from specific page add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ){ if ( get_page_template_slug() == 'template-configurator.php' ) { $page_template = dirname( __FILE__ ) . '/template-configurator.php'; } return $page_template; } /** * Add "Custom" template to page attirbute template section. */ add_filter( 'theme_page_templates', 'wpse_288589_add_template_to_select', 10, 4 ); function wpse_288589_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) { // Add custom template named template-custom.php to select dropdown $post_templates['template-configurator.php'] = __('Configurator'); return $post_templates; }
None of the previous answers was working for mine. Here one where you can choose your template in Wordpress admin. Just put it in your main php plugin file and change
template-configurator.php
by your template name//Load template from specific page add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ){ if ( get_page_template_slug() == 'template-configurator.php' ) { $page_template = dirname( __FILE__ ) . '/template-configurator.php'; } return $page_template; } /** * Add "Custom" template to page attirbute template section. */ add_filter( 'theme_page_templates', 'wpse_288589_add_template_to_select', 10, 4 ); function wpse_288589_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) { // Add custom template named template-custom.php to select dropdown $post_templates['template-configurator.php'] = __('Configurator'); return $post_templates; }
¿Esposible hacer que lasplantillas depáginapersonalizadasestén disponibles desde un complemento?