Ciao 🙂
In questo articolo ti voglio spiegare come fare in modo che l’utente installi dei plugin attivando il tema da te creato. Prima di procedere però assicurati di aver seguito tutta la guida su: Come creo un tema WordPress?.
Detto ciò se sei arrivato fin quì sono fiero di te! Adesso non resta che imparare a far installare dei plugin di default all’utente quando installa ed attiva il tuo tema. Questa cosa è essenziale perché è molto conveniente gestire alcuni dati attraverso dei plugin gratuiti. Seguimi e capirai!
Quali plugin ti servono?
Per prima cosa ci serve un plugin che ci aiuta a caricare i plugin necessari per il tema in automatico. Per farlo devi scaricarti TGM Plugin Activation disponibile come ZIP in questa cartella o a questo indirizzo del sito ufficiale.
Dopo di che ci servirà un plugin che ci permetta di inserire dei campi appositi per gestire ad esempio l’immagine principale della Home o per gestire parametri ad esempio relativi al colore di sfondo o a qualsiasi altra cosa. Questo plugin è Advanced Custom Field Plugin.
A questo punto prendi TGM, il primo scaricato, e se era in uno ZIP estrailo. Estrai la cartella dandogli lo stesso nome dell’archivio ZIP. Dunque vai nella cartella del tuo tema ed incolla la cartella in mezzo a tutti i file.
Quindi per il secondo plugin crea una cartella “lib” se non è già presente sempre dove hai incollato il plugin TGM. Al suo interno crea una cartella chiamandola “plugins” e dunque copia dentro a quest’ultima lo ZIP contenente il plugin Advanced Custom Field (non estrarre il contenuto dallo ZIP!).
Il file functions.php
Il functions.php si occupa di integrare funzionalità di ogni tipo all’interno del tuo tema. Tra queste c’è l’installazione di un plugin così come l’importazione di funzioni javascript. Vedremo in futuro in maggiore dettaglio l’argomento. Ricordati che il codice di questo file viene eseguito quando il tema che se lo porta dietro viene attivato.
Entra con Sublime o qualsiasi altro editor nel tuo tema ed aggiungi il file “functions.php”. A questo punto inserisci questo codice:
<?php /** * Include the TGM_Plugin_Activation class. */ require_once dirname( __FILE__ ) . '/TGM-Plugin-Activation-develop/class-tgm-plugin-activation.php'; add_action( 'tgmpa_register', 'my_theme_register_required_plugins' ); /** * Register the required plugins for this theme. * * In this example, we register two plugins - one included with the TGMPA library * and one from the .org repo. * * The variable passed to tgmpa_register_plugins() should be an array of plugin * arrays. * * This function is hooked into tgmpa_init, which is fired within the * TGM_Plugin_Activation class constructor. */ function my_theme_register_required_plugins() { /** * Array of plugin arrays. Required keys are name and slug. * If the source is NOT from the .org repo, then source is also required. */ $plugins = array( /** This is an example of how to include a plugin pre-packaged with a theme */ array( 'name' => 'Advanced Custom Fields', // The plugin name 'slug' => 'advanced-custom-fields', // The plugin slug (typically the folder name) 'source' => get_stylesheet_directory() . '/lib/plugins/advanced-custom-fields.4.4.11.zip', // The plugin source 'required' => true, ), /** This is an example of how to include a plugin from the WordPress Plugin Repository */ /*array( 'name' => 'Advanced Custom Fields', 'slug' => 'advanced-custom-fields', ),*/ ); /** Change this to your theme text domain, used for internationalising strings */ $theme_text_domain = 'coursetheme'; /** * Array of configuration settings. Uncomment and amend each line as needed. * If you want the default strings to be available under your own theme domain, * uncomment the strings and domain. * Some of the strings are added into a sprintf, so see the comments at the * end of each line for what each argument will be. */ $config = array( 'domain' => $theme_text_domain, // Text domain - likely want to be the same as your theme. */ 'default_path' => '', // Default absolute path to pre-packaged plugins */ 'menu' => 'install-my-theme-plugins', // Menu slug */ 'strings' => array( 'page_title' => __( 'Install Required Plugins', $theme_text_domain ), 'menu_title' => __( 'Install Plugins', $theme_text_domain ), 'instructions_install' => __( 'The %1$s plugin is required for this theme. Click on the big blue button below to install and activate %1$s.', $theme_text_domain ), // %1$s = plugin name */ 'instructions_activate' => __( 'The %1$s is installed but currently inactive. Please go to the <a href="%2$s">plugin administration page</a> page to activate it.', $theme_text_domain ), // %1$s = plugin name, %2$s = plugins page URL */ 'button' => __( 'Install %s Now', $theme_text_domain ), // %1$s = plugin name */ 'installing' => __( 'Installing Plugin: %s', $theme_text_domain ), // %1$s = plugin name */ 'oops' => __( 'Something went wrong with the plugin API.', $theme_text_domain ), // */ 'notice_can_install' => __( 'This theme requires the %1$s plugin. <a href="%2$s"><strong>Click here to begin the installation process</strong></a>. You may be asked for FTP credentials based on your server setup.', $theme_text_domain ), // %1$s = plugin name, %2$s = TGMPA page URL */ 'notice_cannot_install' => __( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', $theme_text_domain ), // %1$s = plugin name */ 'notice_can_activate' => __( 'This theme requires the %1$s plugin. That plugin is currently inactive, so please go to the <a href="%2$s">plugin administration page</a> to activate it.', $theme_text_domain ), // %1$s = plugin name, %2$s = plugins page URL */ 'notice_cannot_activate' => __( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', $theme_text_domain ), // %1$s = plugin name */ 'return' => __( 'Return to Required Plugins Installer', $theme_text_domain ), // */ ), ); tgmpa( $plugins, $config ); } ?>
Il codice ve lo fornisco direttamente prendendolo da chi fornisce il plugin con commenti originali.
Cerco di spiegartelo velocemente elencandoti in ordine quello che accade:
- Viene importato il plugin TGM
- Viene registrato il plugin TGM tramite la function add_action
- Viene definita la function “my_theme_register_required_plugins” che abbiamo passato come parametro alla function add_action
- Definiamo i plugins da importare indicando che il plugin è già presente nella directory lib/plugins del tema
- Nel commento troviamo la modalità per far sì che l’utente invece se lo scarichi da solo dal repository di WordPress
- Impostiamo il nome del nostro tema come nome di dominio
- Definiamo alcuni messaggi da mostrare all’utente
- Infine passiamo plugins e configurazione al plugin TGM
Prova del funzionamento
Arrivati a questo punto entra nel pannello wp-admin del tuo sito. Disattiva il tuo tema attivandone un altro. A questo punto attiva nuovamente il tuo tema. Puoi fare tutto ciò da:
A questo punto ti comparirà un messaggio in alto al pannello di amministrazione. Nel mio caso compare il messaggio per cui il plugin richiesto è disattivato e va attivato. Nel tuo caso ti chiederà prima di installare il plugin:
Non riesco ad accedere a WP-ADMIN
Cerca di eliminare tutti gli spazi che precedono la chiusura o l’apertura del tag <?php ?> nel file functions.php. Abilita il log di debug di WordPress così da individuare possibili problemi. Ti sarà utile in futuro!
Per abilitare il debug entra nel tuo sito ed apri il file “wp-config.php”. A questo punto trova la riga contenente define(‘WP_DEBUG’, false); ed imposta il valore a “true”. Dunque salva ed esci.
Sidebar e Thumbnail
Il file “functions.php” ci può essere molto utile anche per registrare le sidebar presenti nel tema e per aggiungere la possibilità di utilizzare le thumbnails.
La sidebar è la barra laterale che metteremo nella sezione “News” con i widgets. La thumbnail rappresenta l’immagine in evidenza per una pagina.
Dunque torna nel file “functions.php” ed aggiungi queste righe di codice:
<?php if ( function_exists('register_sidebar') ) { register_sidebar(array( 'name'=>'sidebar', 'id' => 'sidebar', 'before_widget' => '<li>', 'after_widget' => '</li>', 'before_title' => '<h3>', 'after_title' => '</h3>', )); } ?> <?php add_theme_support( 'post-thumbnails' ); ?>
Per prima cosa controlliamo se possiamo chiamare la function register_sidebar. Dopo di che chiamiamo la function passandole un array che riempiamo con alcuni dati:
- Name – Il nome della sidebar
- Id – l’id da assegnare alla sidebar
- before_widget – cosa inserire prima del widget
- after_widget
- before_title – cosa inserire prima del titolo
- after-title
Dunque andiamo ad aggiungere il supporto dell’immagine thumbnail.
Risultato
Vai a modificare la pagina Home. Adesso potrai inserire tramite un rettangolino a destra l’immagine in evidenza. Scegli un’immagine e caricala. Clicca su Aggiorna (per salvare il contenuto della pagina Home) ed a questo punto entra nel sito e vai a vedere la pagina Home. Ora ha anche un’immagine:
Ottimo lavoro! Complimenti per essere arrivato fin quì. La prossima volta miglioreremo la home page del sito creando una pagina specifica. Continua a seguire questa serie di articoli per non perdertene nessuno (Come creo un tema WordPress?).
Se hai dubbi o domande non esitare a scrivermi nei commenti ?
Se ti è piaciuto l’articolo seguimi su Facebook e Twitter oppure rimani sempre aggiornato con la newsletter (da 1 a 4 mail al mese!)