plantillas form wordpress

form - include wordpress



WP: ¿usar el archivo en el directorio de complementos como una plantilla de página personalizada? (4)

¿Es posible que un archivo en el directorio de complementos se use como una Plantilla de página personalizada?

Además, ¿cómo se hace un complemento para crear una página?

Estoy desarrollando un complemento para un cliente basado en un tema, él quiere que este complemento haga páginas de ventas mientras puede usar su tema en la página de inicio. Este es un producto que estoy haciendo para su comercialización, por lo que debe ser automatizado a través del plugin.

es posible?

EDITAR

Tengo los ganchos de activación / desactivación en mi archivo principal de complementos, y no está funcionando . Aquí está el código:

$filename = __FILE__; register_activation_hook($filename, ''superActivation''); register_deactivation_hook($filename, ''superDeactivation''); global $myFile; global $fh; global $stringData; global $filename; $myFile = "testFile.txt"; $stringData = "Testing/n"; $fh = fopen($myFile, ''w'') or die("can''t open file"); function superActivation() { global $myFile; global $fh; global $stringData; global $filename; fwrite($fh, $stringData); fclose($fh); } function superDeactivation() { $myFile = "testFile.txt"; unlink($myFile); }


No puedo responder al usuario1912899, pero su recomendación parece ser la solución más elegante. Para usar una plantilla personalizada para reemplazar single-post.php, he implementado el siguiente código. Esto funcionará para cualquier archivo php único personalizado **** que agregue a su complemento. Si no existe, simplemente regresa a lo que WordPress normalmente usa.

add_action(''template_include'', ''my_template_include''); function my_template_include($template) { $file = dirname( __FILE__ ).''/theme/single-''.get_post_type().''.php''; if(file_exists($file)) { $template = $file; } return $template; }


Puedes hacer esto con el hook template_redirect. Aquí está mi código para reemplazar manualmente la plantilla para un tipo de publicación personalizado con uno en el tema si no hay uno en la carpeta de la plantilla. Coloque esto en su archivo de complemento y luego coloque una carpeta debajo de su complemento llamada archivos de tema con sus archivos de tema predeterminados.

//Template fallback add_action("template_redirect", ''my_theme_redirect''); function my_theme_redirect() { global $wp; $plugindir = dirname( __FILE__ ); //A Specific Custom Post Type if ($wp->query_vars["post_type"] == ''product'') { $templatefilename = ''single-product.php''; if (file_exists(TEMPLATEPATH . ''/'' . $templatefilename)) { $return_template = TEMPLATEPATH . ''/'' . $templatefilename; } else { $return_template = $plugindir . ''/themefiles/'' . $templatefilename; } do_theme_redirect($return_template); //A Custom Taxonomy Page } elseif ($wp->query_vars["taxonomy"] == ''product_categories'') { $templatefilename = ''taxonomy-product_categories.php''; if (file_exists(TEMPLATEPATH . ''/'' . $templatefilename)) { $return_template = TEMPLATEPATH . ''/'' . $templatefilename; } else { $return_template = $plugindir . ''/themefiles/'' . $templatefilename; } do_theme_redirect($return_template); //A Simple Page } elseif ($wp->query_vars["pagename"] == ''somepagename'') { $templatefilename = ''page-somepagename.php''; if (file_exists(TEMPLATEPATH . ''/'' . $templatefilename)) { $return_template = TEMPLATEPATH . ''/'' . $templatefilename; } else { $return_template = $plugindir . ''/themefiles/'' . $templatefilename; } do_theme_redirect($return_template); } } function do_theme_redirect($url) { global $post, $wp_query; if (have_posts()) { include($url); die(); } else { $wp_query->is_404 = true; } }


el código david publicado arriba casi funciona para mí. pero parece cubrir todas las publicaciones y páginas para mí. Este código a continuación funciona muy bien para agregar una plantilla a un solo tipo de publicación que es creado por mi archivo de complemento principal

function get_book_post_type_template($single_template) { global $post; if ($post->post_type == ''books'') { $single_template = dirname( __FILE__ ) . ''/themefiles/single-books.php''; } return $single_template; } add_filter( "single_template", "get_book_post_type_template" ) ;

pero tengo problemas para hacer que funcione con plantillas de página personalizadas que no tienen un tipo de post o tienen una página post_type = por ejemplo, digamos que la página personalizada es una página de inicio de sesión de miembro auxiliar para ver mis publicaciones personalizadas. en mi caso, este archivo se llama myaccount.php y lo he incluido en una subcarpeta dentro de mi carpeta de plugins llamada themefiles.

//Add Page and Post Template Files to Current Theme add_action("template_redirect", ''my_account_redirect''); function my_account_redirect() { global $wp; //Set myAccount Custom Page Template if (isset($wp->query_vars[''pagename''] ) == "myaccount") { $templatefilename = ''myAccount.php''; if (file_exists(dirname( __FILE__ ) . ''/themefiles/'' . $templatefilename)) { $return_template = dirname( __FILE__ ) . ''/themefiles/'' . $templatefilename; } do_account_redirect($return_template); } } //Finishing setting templates function do_account_redirect($url) { global $post, $wp_query; if (have_posts()) { include($url); die(); } else { $wp_query->is_404 = true; } }

Cuando hago el código anterior, la plantilla de myaccount aparece en todas las páginas excepto en el hogar, lo que creo es porque está configurado para un blogroll en lugar de una página estática.


PUEDE agregar plantillas de página desde un plugin fácilmente manipulando el caché de la página.

Para personalizar, simplemente edite el siguiente bloque de código dentro del método __construct;

$this->templates = array( ''goodtobebad-template.php'' => ''It/'s Good to Be Bad'', );

Esto está diseñado para un complemento (los archivos de plantilla se buscan en el directorio raíz del complemento). Esto se puede cambiar si lo desea; consulte mi tutorial completo http://www.wpexplorer.com/wordpress-page-templates-plugin/ para obtener más detalles sobre esta solución. Estos archivos también tienen exactamente el mismo formato que si se los incluyera directamente en un tema.

Código completo;

class PageTemplater { /** * A Unique Identifier */ protected $plugin_slug; /** * A reference to an instance of this class. */ private static $instance; /** * The array of templates that this plugin tracks. */ protected $templates; /** * Returns an instance of this class. */ public static function get_instance() { if( null == self::$instance ) { self::$instance = new PageTemplater(); } return self::$instance; } /** * 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'', ); } /** * Adds our template to the pages cache in order to trick WordPress * into thinking the template file exists where it doens''t really exist. * */ public function register_project_templates( $atts ) { // Create the key used for the themes cache $cache_key = ''page_templates-'' . md5( get_theme_root() . ''/'' . get_stylesheet() ); // Retrieve the cache list. // If it doesn''t exist, or it''s empty prepare an array $templates = wp_get_theme()->get_page_templates(); if ( empty( $templates ) ) { $templates = array(); } // New cache, therefore remove the old one wp_cache_delete( $cache_key , ''themes''); // Now add our template to the list of templates by merging our templates // with the existing templates array from the cache. $templates = array_merge( $templates, $this->templates ); // Add the modified cache to allow WordPress to pick it up for listing // available templates wp_cache_add( $cache_key, $templates, ''themes'', 1800 ); return $atts; } /** * Checks if the template is assigned to the page */ public function view_project_template( $template ) { global $post; if (!isset($this->templates[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 ); // Just to be safe, we check if the file exist first if( file_exists( $file ) ) { return $file; } else { echo $file; } return $template; } } add_action( ''plugins_loaded'', array( ''PageTemplater'', ''get_instance'' ) );

Mira mi tutorial sobre esto para más información.

http://www.wpexplorer.com/wordpress-page-templates-plugin/

Espero que esto te ayude en lo que quieres hacer :)