Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Discussione sui post type personalizzati di WordPress – Functions.php o plugin?

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Come molti di voi sanno, la settimana scorsa Syed Balkhi ha partecipato al WordCamp Raleigh 2012. Durante l’evento, uno dei suoi tweet ha scatenato un dibattito. In questo articolo, il nostro fondatore Syed Balkhi discuterà se i Post Type personalizzati di WordPress appartengono al file functions.php o ai plugin. Di seguito riportiamo il tweet che ha dato il via al dibattito:

Dopo il tweet, molte persone rispettabili della Community di WordPress sono intervenute. Potete vedere l’intera conversazione qui. Curtis McHale ha fatto un ulteriore passo avanti e ha approfondito l’argomento nel suo nuovo articolo sul blog.

La conversazione su Twitter ha portato alla luce alcuni punti importanti.

Riassunto degli argomenti

Argomento dei plugin: L’utente avrà sempre i dati anche se cambia tema. Potrebbero non avere un aspetto gradevole, ma rimarranno lì.

Argomento di Functions.php: I dati senza design sarebbero irrilevanti. Confonderebbe ancora di più gli utenti.

Con quale delle due parti siete più d’accordo? Chiaramente entrambe le parti hanno i loro problemi, ma qual è il male minore?

Ecco perché riteniamo che i Post Type personalizzati debbano SEMPRE essere inseriti in un plugin specifico per il sito o in un plugin separato.

Lunga vita ai dati

I tipi di contenuto personalizzati sono dati. Nella maggior parte dei casi, i dati sopravvivranno al design attuale. Avendo cambiato tema diverse volte, capiamo bene questa affermazione. Post, Pagine, Collegamenti, Allegati e Revisioni sono tutti post type / tipi di contenuto integrati in WordPress. In alto abbiamo post type / tipi di contenuto come Libri, Testimonianze, Offerte, ecc. Immaginate se, cambiando tema, tutti questi tipi sparissero? Di certo non vorremmo che ciò accadesse.

Avendo degli sviluppatori nel nostro team, questo non dovrebbe avere molta importanza. Considerando che tutti i nostri temi sono personalizzati dal nostro team, che differenza fa? Il segreto sta in due parole: tempo e centralizzazione. Se disponiamo di tutti i dati necessari, in futuro dovremo solo modificare lo stile. Non dovremo preoccuparci di copiare e incollare ogni volta le funzioni da un file all’altro. E se si volesse replicare la funzionalità? Basta prendere il plugin e inserirlo nel nuovo sito. Modificate lo stile e il gioco è fatto.

Regole e standard

Quando si usa la parola SEMPRE, come abbiamo fatto nel nostro tweet, può significare sia regola che standard. Sia le regole che gli standard sono fatti per la maggioranza. Ci saranno sempre casi particolari in cui le regole vengono infrante e gli standard violati, ma questo non significa che dovremmo eliminare del tutto gli standard.

Ci sono tonnellate di post type generici che richiedono per lo più la stessa serie di meta-campi aggiuntivi. Alcuni esempi che mi vengono in mente sono: Citazioni, Libri, Ricette, Testimonianze, Portfolio, ecc.

Considerando il gran numero di temi per la fotografia e per il portfolio disponibili sul mercato gratuito e commerciale, non ha quasi senso costringere l’utente a inserire nuovamente tutte le informazioni sui post type / tipo di contenuto personalizzati ogni volta che cambia tema. Vediamo un esempio di scenario:

Fotografo – L’utente ha configurato un WordPress con funzionalità di blog (CPT “articolo” predefinito). Vuole aggiungere un portfolio dei suoi lavori (è necessario un CPT Portfolio). Vuole mostrare le testimonianze dei clienti (è necessario un CPT Testimonial). Tutte queste informazioni sono sicuramente destinate a vivere oltre il design del tema. Un anno dopo, l’utente vuole cambiare l’aspetto del suo sito e dargli una ricarica. Trova un nuovo tema che ha tutte le funzioni simili. Nel momento in cui cambia tema, BOOM. Tutti i dati inseriti in precedenza sono scomparsi. C’è un menu chiamato Portfolio e un menu chiamato Testimonianze, ma nessuno dei dati è presente. L’utente pensa: “Accidenti, ho perso tutti i miei contenuti”. Crea una nuova domanda di supporto nel forum. Invia email a siti come WPBeginner, ecc. Se non riceve una buona risposta, deve inserire nuovamente tutti i dati. Questa è una pessima esperienza per l’utente.

Come possiamo risolvere questo problema?

Possibile soluzione?

Creare una nuova base standard. Justin Tadlock ha già iniziato a lavorare in corso d’opera su questo problema creando un plugin per il portfolio di base. Sarà la soluzione perfetta per tutti? NO, ma lo sarà per la maggior parte.

Come chiede Justin nel suo articolo, quali campi standard dovrebbero essere inclusi nel plugin per il portfolio (referer ai meta). Questo tipo di conversazione deve avvenire tra gli sviluppatori che stanno creando funzionalità simili nei loro temi. Perché copiare e incollare la stessa cosa da un tema all’altro quando è possibile farlo tramite un plugin? Una volta diventato uno standard, gli altri autori di temi inizieranno ad adattarsi.

Ad esempio, stiamo assistendo a un aumento del supporto stilistico per Gravity Form nei framework per temi WordPress come Genesis e altri. Perché? Perché hanno capito che i loro utenti lo usano.

Esistono temi WordPress robusti e ricchi di funzionalità che, a nostro avviso, dovrebbero essere plugin. Temi per le bacheche di lavoro, temi per la tracciabilità dei problemi, temi per gli annunci, temi per il settore immobiliare, ecc. Dovrebbero essere tutti powered by un plugin di base. Sta già accadendo con WooCommerce. WooThemes ha versione numerosi temi che hanno un supporto stilistico integrato per il plugin. Anche altre aziende produttrici di temi hanno promesso di rilasciare versioni di temi per l’e-commerce basate su WooCommerce. È possibile passare da un tema all’altro e mantenere tutti i prodotti così come sono. È come se il tema fosse cambiato, ma tutto fosse tornato al suo posto. Questa è l’esperienza di cambio tema a cui dobbiamo aspirare.

Perché non fare la stessa cosa con Portfolio, Testimonianze e altri post type / tipi di contenuto generici? È perché è troppo semplice, mentre l’e-commerce è una bestia più grande da conquistare? È chiaro che l’e-commerce ha troppi campi rispetto agli altri, quindi dovrebbe essere molto più facile per questi post type generici. Si tratta solo di fare uno sforzo consapevole per migliorare le cose.

Date un’occhiata al plugin ReciPress. Crea un metabox personalizzato con i campi delle ricette e lo allega agli articoli. Tuttavia, è possibile allegarlo a post type / tipo di contenuto personalizzati. Chiunque utilizzi questo plugin può cambiare tema senza dover affrontare una tale seccatura.

Sarebbe bello vedere temi come AgentPress powered by un plugin di base centralizzato. Sarebbe bello vedere la transizione del cambio di tema diventare più facile. Ad esempio, se un utente passa da un tema fotografico a un altro, non dovrebbe essere un caos. Potrebbero verificarsi errori minori, ma almeno nel quadro generale le cose funzioneranno.

È sempre possibile fornire esempi di post type / tipo di contenuto super personalizzati creati per l’uso di un solo cliente, ma questa è l’eccezione, non la regola.

Cosa ne pensate di questo argomento? Dove dovrebbe risiedere il codice dei post type / tipo di contenuto? Nel file functions.php o nei plugin?

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

34 commentiLascia una risposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Yazmin says

    Having been on the end of losing my CPTs numerous times as I switched themes, I find it frustrating to have to set up the same functionality over and over again in functions.php.

    I completely prefer the plugin route and that is the method I will be using from here on out for my business projects as well.

  3. Joshua Jarvis says

    Having this exact issue with a real estate theme. The “listings” were all custom types in a theme that is now functionally obsolete. When I went to upgrade the theme I lost all the custom post content, now I have to figure out a way to transfer it all. I have options, but if it were plugin, this wouldn’t be necessary.

  4. Hugh H. Sands says

    “We won’t have to worry about copying and pasting the functions from one file to another every single time.”
    I can’t imagine someone writing code for a CPT in functions.php when it’s so easy to isolate it with includes

    This debate goes most of the times around data vs design and I wonder, being quite new to WP, what about performance? Do plugins impose any overload?

  5. Kelvin Alfonso says

    I’ve always included CPT’s through a separate file into the functions.php but I think I’ll be switching over to the plugins route. Thank you!

  6. Sudhakar says

    I am a beginner and I have no expertise to comment one way or the other in favor or against of a plug-in or functions.php. But I am wondering if I want to go the functions.php route and do it under a child theme, what is the problem then? Why do I need to have it in a plug-in, wouldn’t my child theme save me from future theme upgrades and changes in the themes?

    • Editorial Staff says

      Your child theme would save you from future theme updates. However, it will NOT save you if you change your themes. Because you change the child theme if you change the active theme.

      Admin

  7. Pat Ramsey says

    I’m a believer in the plugin route for custom post types & taxonomies. The author’s mention of a site-specific plugin is how I do it. I place any custom post types, custom taxonomies & metaboxes in this plugin, tailored for the site’s purpose. Eventually the site’s theme will change but the data lives on & is still easily accessible.

  8. shawn says

    If developers continue to ignore the fact that separating “data” from for “design” is necessary to create modular apps, and it does not matter where it is the data placed, reusing that data / code will always be problem.

    There seems to be a perception by some in the WP community, for one reason or the other that you can only access data in the WordPress ecosystem if it is wrapped in a plugin so we keep seeing discussions like this contributing to “The great plugin vs theme debate”.

    Focus needs to placed on evolving the WordPress’ archaic plugin system, to creating libraries based on a modular design patterns that separate code / data from design. Libraries that can be used in both themes and plugins….

    Debates like these are pointless in the WP post PHP4 era!!! (re-post)

  9. Mark Simchock says

    Re: “As Justin asks in his post, what standard fields should be included in the portfolio plugin (referring to post meta). This type of conversation needs to happen among developers who are creating similar functionality in their themes.”

    Moi? I would prefer a well documented plugin that’s engineered to be enhanced than a “closed”, one size fits all approach that difficult to work with (that code).

    My point is, perhaps it’s possible to say, “I’m not trying to be all things to all people. Here’s my basic plugin. Here’s how you trick it out. It’s designed to be tricked out.” and just leave it at that. No matter what you do it’s difficult to anticipate every use case, every use need. So why bother? Why not approach it as a framework (of sorts) and let the dev in need just customize as needed?

    • Justin Tadlock says

      That’s actually the plan. I’m building an extremely small and easily-customizable base. But, I’d like to know what, if any, fields should be standard.

  10. Affan Ruslan says

    I believe it should be on plugin.
    In case the user might not need the data in future, they can always convert the custom post type post to the “normal” post type. There’s plugin to do so, search in the repo and you’ll find at least one.

  11. Christophe Debruel says

    I don’t really care what people say. Custom post type goes into a plugin. A theme can easily be modified to fit the custom post type in the frontend. I find it more logic to style the theme for the CTP than having different themes with the same CTP code.

  12. Elliott Richmond says

    Plugin for me. At least for a non technical client, although the theme might not function correctly it will become apparent that there is a problem and that will prompt them to get a developer onboard.

  13. Kailas Mahajan says

    Its all depend on the project…
    if one handling project which needs to change theme after a certaine period of time…can use plugin..

    or if project which are sticking with the one theme.. can go with function.php

  14. Ross W says

    Everyone’s talking about how the data needs to be styled by the theme, and examples where that’s the case and where the data and theme can be separated.

    What I don’t see is anyone talking about cases where a theme depends on having some specific data available. Lets say you have a theme that has a map of countries and some country-specific data, and that, without that map and data the theme loses some of its key functionality.

    Yes, you could still do this with the data in a plugin, but is it reasonable for a theme to assume that some data exists? Is it reasonable to assume that the plugin that creates the data types is installed and enabled? (Genuine questions…discuss!)

    What if my slightly non-technical client wants to create a copy of the site with their ‘theme’. They enable the theme on a new WordPress install only to find that a whole load of stuff is missing or broken? They thought that the theme contained all that they needed for their site to look right?

    I can see uses for both approaches. For most of my client work I set up CPT’s, meta-boxes, and some functions to make accessing them simple, in library files and include them. This keeps all the ‘stuff’ that my theme needs to work in one package, but keeps it simple to move the CPT’s to a new theme should I want to.

    Of course, if a CPT looks like it could be used across multiple themes and isn’t SO specific that it only really applies to a single client’s data then you turn it into a plugin that can be deployed at will.

    I don’t think there’s a simple, one-way relationship between data and themes. It’s not always the case that ‘I have some data that needs styling’…sometimes ‘my styling needs some data’.

    Thoughts on that?

    • Andres Hermosilla says

      I definitely agree that there is a benefit to having one “complete” package. Often times there is very theme specific functionality that is better to be tied in directly (i.e. P2 from Auttomatic) vs. installed theme and theme plugin.

  15. Curtis McHale says

    Your reference to AgentPress is one of the reasons I’m 100% for CPT’s in plugins. I’ve had to deal with themes like that and it’s so hard to skin them properly unless you remove the custom function from the theme. My client and I spent 20 hours getting the code to a point we could actually work on it.

      • Birgit says

        The plugin is a “toolbox” for code snippets, that you do normally in your functions.php.
        But with a theme update, custom code in the theme’s function.php might get lost.
        So I use within my network installation this plugin, activated it network-wide and then the plugin comes with “modules”, that you can access for example by FTP.
        You can create modules as much as you like – I have one for each of my blogs within this network. In this modules (= just .php files, let’s say just like site-specific plugins) you can add all the code, that you normally put in your theme’s function.php.
        Then at the options page of the plugin you can activate in each blog, which module you would like to load and whether to load it only for frontend or only for backend or for both.
        So I only need to have 1 plugin to serve all blogs with individual code snippets, that normally go to their functions.php – and can decide, where to load these modules.
        uff, hope this is understandable, because my English is not the best ;-)

        Perhaps this will work for you to read it: http://tinyurl.com/bf5dflt

        • Editorial Staff says

          Brigit, I did translate the WP.org page as well. I understood what the plugin was intended for. However the screenshots were in German, and google is not smart enough to translate images just yet. Same issue is with the link you posted :)

  16. Sara says

    I always prefer plugins over functions.php for anything that would materially “break” on the front end or lose data if the theme were changed. This is for precisely the reasons you cite, and I also feel that it is NUTSO for those of us who are not really php programmers to try to troubleshoot conflicts when you have to be commenting out stuff in functions.php to isolate a problem.

    • Editorial Staff says

      The idea is that you should register CPT’s in a site-specific plugin. There is not a specific plugin out there yet. But this is just tossing around the idea of creating a base plugin for generic post types.

      Admin

  17. Muhammad Waqas says

    I’m more convinced with the use of local functions. but in this case I think plugin can be trusted more. For example if you start using wp with a specific framework. In most of cases It possible that you’ll become a slave for a long time unless until you hire a wp professional to help you escape from that framework without losing your settings and data. On the other hand plugins can work at almost at every theme.

    When I started working with wp I preferred framework over plugin. The reality is that plugin developer consider newbie and less literate people when developing something. I personally believe that most part of wp users like manual code hacks than depending on plugins for core functions of sites. in long term plugins aren’t reliable. I fee so..

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.