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

Debate sobre tipos de postagem personalizados do WordPress – Functions.php ou plug-ins?

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Como muitos de vocês sabem, na semana passada Syed Balkhi participou do WordCamp Raleigh 2012. Durante o evento, um de seus tweets provocou um grande debate. Neste artigo, nosso fundador Syed Balkhi debaterá se os Custom Post Types do WordPress devem estar no arquivo functions.php ou nos plugins. Abaixo está o tweet que deu início a esse debate:

Após o tweet, muitas pessoas de renome na comunidade do WordPress se manifestaram. Você pode ver a conversa completa aqui. Curtis McHale deu um passo adiante e elaborou o tópico em sua nova postagem no blog.

A conversa no Twitter trouxe alguns pontos importantes.

Resumo dos argumentos

Argumento dos plug-ins: O usuário sempre terá os dados, mesmo que mude o tema. Pode não parecer tão bonito, mas permanecerá lá.

Argumento do Functions.php: Os dados sem design seriam irrelevantes. Isso confundirá ainda mais os usuários.

Com qual lado você concorda mais? Claramente, os dois lados têm seus problemas, mas qual é o menor de dois males?

Aqui está o motivo pelo qual acreditamos que os Custom Post Types SEMPRE devem estar em um plug-in específico do site ou em um plug-in separado.

Vida longa aos dados

Os Custom Post Types são dados. Na maioria dos casos, seus dados sobreviverão ao design atual. Tendo mudado nossos temas algumas vezes, entendemos essa afirmação claramente. Posts, Páginas, Links, Anexos e Revisões são todos os tipos de post types que vêm embutidos no WordPress. Além disso, temos tipos de post como Livros, Depoimentos, Ofertas etc. Já imaginou se mudássemos um tema e todos esses tipos desaparecessem? Certamente, não gostaríamos que isso acontecesse.

Como temos desenvolvedores em nossa equipe, isso não deve ter muita importância. Considerando que todos os nossos temas são projetados de forma personalizada por nossa equipe, que diferença isso realmente faz? O segredo está em duas palavras: tempo e centralização. Desde que tenhamos todos os dados necessários, tudo o que precisaremos fazer no futuro é alterar o estilo. Não precisaremos nos preocupar em copiar e colar as funções de um arquivo para outro todas as vezes. E se você quiser replicar a funcionalidade? Basta pegar o plug-in e colocá-lo em seu novo site. Altere o estilo e pronto.

Regras e padrões

Quando você usa a palavra ALWAYS, como fizemos em nosso tweet, ela pode significar tanto regras quanto padrões. Tanto as regras quanto os padrões são feitos para a maioria. Sempre haverá casos especiais em que as regras são distorcidas e os padrões são violados, mas isso não significa que devemos nos livrar completamente dos padrões.

Há muitos tipos de posts genéricos que, em sua maioria, exigem o mesmo conjunto de metacampos adicionais. Alguns exemplos que me vêm à mente são: Citações, Livros, Receitas, Depoimentos, Portfólio etc.

Considerando o grande número de temas de fotografia e portfólio disponíveis no mercado gratuito e comercial, quase não faz sentido fazer com que o usuário insira novamente todas as informações do tipo de postagem personalizada sempre que mudar de tema. Vamos dar uma olhada em um exemplo de cenário de caso:

Fotógrafo – O usuário configurou um WordPress que tem uma funcionalidade de blog (CPT padrão “post”). Ele deseja adicionar um portfólio de seu trabalho (requer um CPT de portfólio). Ele quer mostrar depoimentos de clientes (requer um CPT de depoimento). Todas essas informações certamente sobreviverão ao design de um tema. Um ano depois, o usuário quer mudar a aparência de seu site e atualizá-lo. Encontra um novo tema que tem todas as características necessárias para o design do tema. Encontra um novo tema que tem todas as funções semelhantes. No momento em que ele muda o tema, BOOM. Todos os dados anteriores que ele inseriu desapareceram. Há um menu chamado Portfólio e um menu chamado Depoimentos, mas nenhum dos dados está lá. O usuário pensa: “Puxa vida, perdi todo o meu conteúdo”. Cria uma nova pergunta de suporte no fórum. Envia e-mails para sites como o WPBeginner etc. Se não receberem uma boa resposta, terão que inserir novamente todos os dados. Essa é uma experiência ruim para o usuário.

Então, como podemos resolver esse problema?

Possível solução?

Criamos uma nova base padrão. Justin Tadlock já começou a trabalhar nesse problema há algum tempo, criando um plug-in de portfólio básico. Essa será a solução perfeita para todos? NÃO, mas será para a maioria.

Como Justin pergunta em sua postagem, quais campos padrão devem ser incluídos no plug-in de portfólio (referindo-se à meta da postagem). Esse tipo de conversa precisa acontecer entre os desenvolvedores que estão criando funcionalidades semelhantes em seus temas. Por que copiar e colar a mesma coisa várias vezes de um tema para outro quando isso pode ser feito por meio de um plug-in? Quando isso se tornar um padrão, outros autores de temas começarão a se adaptar a ele.

Por exemplo, estamos vendo um aumento no suporte de estilo para o Gravity Forms em estruturas de temas do WordPress, como o Genesis e outros. Por quê? Porque eles entendem que seus usuários estão usando isso.

Há alguns temas robustos do WordPress que vêm carregados de funcionalidades que acreditamos que deveriam ser plug-ins. Temas de quadro de empregos, temas de rastreamento de problemas, temas de anúncios classificados, temas de imóveis etc. Todos eles deveriam ser alimentados por um plug-in básico. Isso já está acontecendo com o WooCommerce. A WooThemes lançou vários temas com suporte de estilo incorporado para o plug-in. Outras empresas de temas prometeram lançar também temas de comércio eletrônico baseados no WooCommerce. Você pode mudar de um tema para outro e manter todos os seus produtos como estão. É quase como se o tema tivesse mudado, mas tudo se encaixasse no lugar. Essa é a experiência de mudança de tema pela qual precisamos nos esforçar.

Por que não fazer a mesma coisa com Portfólio, Depoimentos e outros tipos de post personalizados genéricos? Será que é porque é muito simples em comparação com o comércio eletrônico, que é uma fera maior a ser conquistada? Claramente, o comércio eletrônico tem muitos campos em comparação com os outros, portanto, deve ser muito mais fácil para esses tipos de post genéricos. É apenas uma questão de fazer um esforço consciente para melhorar as coisas.

Dê uma olhada no plugin ReciPress. Ele cria uma metabox personalizada com campos de receita e a anexa aos posts. No entanto, é possível anexá-la a tipos de post personalizados. Qualquer pessoa que use esse plug-in pode mudar de tema sem ter que passar por esse incômodo.

Seria bom ver temas como o AgentPress serem alimentados por um plug-in de base centralizado. Seria ótimo ver a transição da mudança de temas se tornar mais fácil. Por exemplo, se um usuário mudar de um tema de fotografia para outro, não deve ser um caos. Podem ocorrer pequenos erros, mas, pelo menos, em termos gerais, as coisas funcionarão.

Você sempre pode dar exemplos de tipos de post superpersonalizados criados para uso único do cliente, mas isso é a exceção, não a regra.

O que vocês pensam sobre esse tópico? Onde deve residir o código dos tipos de post personalizados? No arquivo functions.php ou nos plug-ins?

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

34 ComentáriosDeixe uma resposta

  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.

      Administrador

  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.

      Administrador

  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..

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.