adicionar um modelo de página personalizado a partir do 'plugin'

estou a trabalhar na construção do meu primeiro plugin para o wordpress e estou a precisar dele para adicionar dinamicamente uma página personalizada para uma tela de login, entre outras coisas.

a única coisa que consegui descobrir que está perto do que estou a precisar é aqui: WP-Use o ficheiro no directório do plugin como modelo de página personalizado? & é possível adicionar uma página de modelo personalizada num 'plugin' de WP?Mas ainda não são bem o que procuro.

Aqui está o código que tenho em execução. no meu plugin...

// Add callback to admin menu
add_action( 'template_redirect', 'uploadr_redirect' );

// Callback to add menu items
function uploadr_redirect() {

global $wp;
$plugindir = dirname( __FILE__ );

// A Specific Custom Post Type
if ( $wp->query_vars["post_type"] == 'uploadr' ) {

    $templatefilename = 'custom-uploadr.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;

    }

}

Usar isto requer que o meu cliente crie uma nova página... o que eu estou precisando é que o plugin para criar automaticamente uma página personalizada (com um caminho personalizado, o que significa .com/customompathhere) usando um arquivo de modelo a partir da pasta plugin, que irá então conter todas as ações que o plugin executa.

Nota: Este plugin foi concebido para correr numa página, reduzindo assim o tempo de carga e etc.

Obrigado antecipadamente!

Author: Community, 2013-10-12

2 answers

Aqui está a minha solução de código para adicionar modelos de página de um plugin Wordpress (inspirado por Tom McFarlin).

Isto é desenhado para um 'plugin' (os ficheiros de modelos são procurados na pasta de topo do 'plugin'). Estes arquivos também estão exatamente no mesmo formato como se fossem para ser incluídos diretamente em um tema. Isto pode ser alterado se desejar-confira meu tutorial completo http://www.wpexplorer.com/wordpress-page-templates-plugin / para mais detalhes sobre isto solucao.

Para personalizar, basta editar o seguinte bloco de código dentro do método __construir;

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

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' ) );

Veja o meu tutorial sobre isto para mais informações.

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

([3]} espero que isto te ajude no que queres fazer:)
 5
Author: Harri Bell-Thomas, 2014-02-28 23:36:40
Na verdade, consegui falar com um amigo meu, depois de rever o código. Aqui está...
<?php

    register_activation_hook( __FILE__, 'create_uploadr_page' );

    function create_uploadr_page() {

        $post_id = -1;

        // Setup custom vars
        $author_id = 1;
        $slug = 'event-photo-uploader';
        $title = 'Event Photo Uploader';

        // Check if page exists, if not create it
        if ( null == get_page_by_title( $title )) {

            $uploader_page = array(
                    'comment_status'        => 'closed',
                    'ping_status'           => 'closed',
                    'post_author'           => $author_id,
                    'post_name'                     => $slug,
                    'post_title'            => $title,
                    'post_status'           => 'publish',
                    'post_type'                     => 'page'
            );

            $post_id = wp_insert_post( $uploader_page );


            if ( !$post_id ) {

                    wp_die( 'Error creating template page' );

            } else {

                    update_post_meta( $post_id, '_wp_page_template', 'custom-uploadr.php' );

            }
        } // end check if

    }

    add_action( 'template_include', 'uploadr_redirect' );
    function uploadr_redirect( $template ) {

        $plugindir = dirname( __FILE__ );

        if ( is_page_template( 'custom-uploadr.php' )) {

            $template = $plugindir . '/templates/custom-uploadr.php';
        }

        return $template;

    }

?>
 1
Author: Designer 17, 2013-12-17 16:03:22