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

Como usar os tipos de post personalizados no WordPress 3.0

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.

Desde a versão 2.9, o WordPress introduziu a capacidade de usar tipos de post personalizados. Agora, com a versão 3.0, as coisas foram levadas um pouco mais longe com a opção de criar painéis para seus tipos de postagem personalizados. Neste tutorial, mostraremos como implementar tipos de postagem personalizados em seu site do WordPress.

Criação de tipos de post personalizados – Uso de plug-ins

A partir da versão 3.0, o WordPress não tem nenhuma UI (interface de usuário) integrada para criar tipos de post personalizados. Há apenas duas opções que podemos usar para criar tipos de post personalizados: plugins ou codificá-los no arquivo functions.php do seu tema. Primeiro, vamos dar uma olhada em como podemos usar plugins para criar tipos de post personalizados.

IU do tipo de post personalizado

Custom Post Types UI

OCustom Post Type UI é um plugin desenvolvido por Brad Williams, da WebDevStudios, que permite criar facilmente tipos de posts e taxonomias personalizados. Um dos recursos mais interessantes desse plug-in é que ele gera um código para criar tipos de post personalizados, para que você possa colá-lo no arquivo functions.php do seu tema. Uma das peculiaridades desse plug-in é a incapacidade de compartilhar taxonomias entre todos os seus post_types.

Generate code for Custom Posts Types

No painel Custom Post Type UI, clique em “Add New” (Adicionar novo).

Add New Button for Custom Post Type UI

Em seguida, você receberá algumas opções para preencher. O “Post Type Name” (Nome do tipo de postagem) é o que será usado pelo WordPress para consultar todas as postagens desse post_type. O “Label” (Rótulo) é o que será exibido na barra lateral de seu Dashboard, assim como o menu “Post” normal. Se você expandir a opção “View Advanced Options” (Exibir opções avançadas), verá mais algumas opções que podem ser configuradas. A maioria delas é autoexplicativa, como “Public” (Público) e “Show UI” (Mostrar interface do usuário). A primeira, quando definida como verdadeira, permite que o menu do tipo de postagem personalizada seja exibido na barra lateral, e a outra (show ui), quando definida como verdadeira, gera o painel do menu.

“Rewrite” é o que permite que o tipo de postagem personalizada use URLs do WordPress amigáveis para SEO (Permalinks). O “Custom Rewrite Slug” pode ser definido como qualquer coisa que você quiser. O WordPress usará esse slug para gerar os permalinks. Portanto, se tivermos example.com com um slug de reescrita personalizado de “movies”, o permalink do seu tipo de postagem personalizada será semelhante a example.com/movies

A função “Query Var” do WordPress permite que você consulte o post do seu tipo de post personalizado. Portanto, se usarmos o exemplo dado anteriormente, para acessar uma postagem com o título My First Movie Post (Minha primeira postagem de filme), que está escrita no post_type Movies (Filmes), podemos digitar example.com/?movies=my-first-movie-post (Minha primeira postagem de filme). Portanto, a variável de consulta tem a seguinte aparência: ?posttypename

Por fim, você pode escolher os diferentes recursos compatíveis com seu tipo de post personalizado, como miniaturas/imagem em destaque e trechos.

Custom Post Types UI Options

Criação de tipos de post personalizados – Uso do arquivo Functions.php

Hard Code Custom Post Types

Se você preferir usar tipos de post personalizados sem um plug-in, basta adicionar o seguinte código ao arquivo functions.php do seu tema:

// Creates Movies post type
register_post_type('movies', array(
'label' => 'Movies',
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug' => 'movies'),
'query_var' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'thumbnail',
'author',
'page-attributes',)
) );

Vamos dissecar o código.

register_post_type( $post_type, $args ): Essa função aceita dois parâmetros, $post_type ou o nome do tipo de postagem, e $args, uma matriz de argumentos.

label: Nome plural dado ao tipo de postagem que é exibido na barra lateral do painel de administração.

public: true/false. Permite que a interface do usuário do administrador seja preenchida com publicações desse tipo.

show_ui: true/false. Mostra ou oculta uma interface do usuário padrão para gerenciar esse tipo de postagem.

capability_type: Padrão: post Tipo de post a ser usado para verificar os recursos de leitura, edição e exclusão.

hierarchical: se o tipo de post é hierárquico.

rewrite: true/false. Padrão: true Se o argumento slug for inserido, o nome do slug será anexado às postagens.

query_var: true/false Define o nome do tipo de post como uma variável de consulta.

supports: Padrão: title e author Define os diferentes recursos de suporte permitidos pelo tipo de post.

Visite o WordPress Codex para obter mais informações sobre register_post_type().

Exibição de publicações de tipo de postagem personalizada

Para exibir as postagens de seu tipo de postagem personalizada, adicione os seguintes códigos no loop. Substitua “name” pelo nome de seu tipo de postagem. Observação: Não é necessário adicionar os tipos de post personalizados em seu arquivo index.php. Você pode criar uma página personalizada do WordPress e executar a seguinte consulta dentro do loop.

$query = new WP_Query( 'post_type=name' );

Para exibir postagens de mais de um tipo de postagem, altere o código acima para o seguinte. Altere movies pelo nome de seu tipo de postagem personalizado.

$query = new WP_Query( array(
	'post_type' => array( 'post', 'movies' )
) );

O código acima exibirá todas as postagens do tipo de postagem normal (post) e do tipo de postagem personalizado, movies.

É isso aí. Esperamos que este tutorial tenha sido útil e não se esqueça de postar suas dúvidas nos comentários.

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

59 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. dave says

    Ive created two custom post types but only the first one is showing on my page. ive added this
    $query = new WP_Query( array( ‘post_type’ => array( ‘post’, ‘featured’, ‘latest’ )
    ) );

    inside my loop file but nothing. how can i resolve this?

  3. wizdom networks says

    Firstly, great article! I’m working through implementing custom post types via code. Noteworthy that the current WordPress documentation (http://codex.wordpress.org/Function_Reference/query_posts) specifies that the query_posts function should generally not be used and that the pre_get_posts hook is used to modify queries.

    “It is strongly recommended that you use the pre_get_posts filter instead, and alter the main query by checking is_main_query”

    Again, great article, thanks for sharing.

    Cheers.

  4. Thom Abbott says

    WOW…for a novice who uses WP to run their website, this is not Beginner stuff by any means! I’ll probably have to reach out to some WP developer to set up my Custom Page that I want.

  5. mark shirley says

    query_posts( ‘post_type=movies’);
    ?>

    I cant get this to work in my twentyeleven child theme page template where would i put it to pull a page of movies. Actually its the excerpts i really want. Thanks Mark

  6. muntzdesigns says

    When using this plugin and adding the above code to loop.php you will lose control over categories…my custom post type is added to all categories…any help?

    • wpbeginner says

      @muntzdesigns This is why you have multiple loops… your main blog loop, archive.php, category.php etc… On a custom designed site, you will have to utilize that in order for this to work appropriately.

      • muntzdesigns says

        @wpbeginner@muntzdesigns So just add the above code to all files? (loop.php, archive.php and category.php). Thanks.

        • wpbeginner says

          @muntzdesigns No. You only add the code on the front pages. The issue you had was that custom post types were being added to all categories… You need to add the above code only to the main loop. Then create a new loop for category archive, taxonomy archive, author archive …

  7. dazuaga says

    What exactly does Content Type Identifier in CMS Press plugin? I’m looking for a way to prepend a the category slug to the custom post type (example.com/category/post_type/postname) but when using %category%/%identifier%/%postname% in Content Type Identifier automaticaly transforms this way: %categoryidentifierpostname

  8. simplywendz says

    This is such a great tutorial for creating a custom post in wordpress. The steps are given on details one could easily follow. This is a big, big help!

  9. Cupbearer says

    Wow, I had the whole CMS Press thing working, but couldn’t figure out how to get it to show up in the posts. I guess it’s been around for so long that everyone just assumes that it should already be known. Perfect Answer to getting my Custom Post Type to show up in the Loop.

    Jerry Craig
    Cupbearer

  10. Ed says

    I have tried the plugin, very impressive. However, I am trying to get a page attribute to appear from my themes ‘Pages’ attributes i.e the ability to use a full width page option. Am I to assume that your plugin only pulls attributes from Post type layouts rather than Page type layouts? All I want is to have the option of setting a post to a full, pre-determined template.

    Great job though – I shall be using this a lot.

    Cheers
    Ed

  11. Simon says

    I have tried the plugin way but couldn’t get the post to show up. Maybe that’s because I coulndn’t find the loop.php file.

    Anyways, thanks a lot, I’m pretty sure it will work sometime soon.

    I want to say that one super awesome thing that would be great to do with wordpress is to have the possibility to create custom views of content just like in drupal with the views module.

    I know there is a plugin called pods and pods cms that is suppose to make that possible. Perhaphs you could ask the developper to help out in a post on wpbeginner if you do not understand it at all like me. I’m sure lots of people would love this. Presenting views is what realy makes a cms a realy dynamic cms after all.

  12. Peter says

    Good tutorial, thank you for sharing.

    I have a question on this.
    I made a custom post type through functions.php (a calendar) which has a custom meta box in the admin UI. This meta box uses jQuery on one field.(http://jqueryui.com/demos/datepicker/).
    For this datepicker to work, I need to embed the required scripts.
    add_action(‘admin_enqueue_scripts’,’enqueue_my_scripts’);
    works but my scripts get loaded on the entire admin UI. (which interferes with the default WP admin jquery)
    So what I need is the hook for my custom post type.
    this:
    add_action(‘register_post_type’,’enqueue_my_scripts’);
    doesn’t work because register_post_type isn’t a hook.
    So, what is the hook for a custom post_type?

    • Amanda says

      You could try adding the following to your function definition before registering the script:

      if(is_admin()) return;

      So something like:

      function some-function(){
      // we don't need this on admin pages, so...
      if(is_admin()) return;
      //register the custom script
      wp_enqueue_script( 'some-script' );
      }

  13. Evan says

    How do I get each content type to show up in the loop? I mean, it’s almost like Tumblr. If I post a picture… I need to customize the code in the loop – same thing I post a link.

  14. Michael says

    I cannot seem to get the loop to work to query posts of my custom type. Your example seems easy enough so I tried the following $var = query_posts( ‘post_type=sponsor’);

    Then I started a loop
    while ($var ->have_posts()) : $var ->the_post();
    Do stuff
    endwhile;

    this returns a php error:
    Fatal error: Call to a member function have_posts() on a non-object in single-sponsor.php on line 22

    line 22 is the line with the while loop.

    Ideas? What am I doing wrong?

  15. Romero says

    I have tried to create a tag for custom field, and when I use get_the_tags within the loop of custom type, it doesn’t print anything.
    Any suggestions?

  16. Jan says

    Im very excited about this new feature ^-^ You made a nice video. Altough in your example, why use custom post types and not just make up a category books and movies for the posts? That way you save all the hassle of a custom post type.

    • Editorial Staff says

      First, it lets you organize things differently. Second, you can have a completely different write panel with different options. It allows for much more customizations…

      Administrador

  17. Sandra says

    Thanks for this great article! I’m a real wp beginner, and maybe you can help me with this question:
    Is it possible to display archives of one custom post type in the sidebar like one can do by using the “display archives by cat”-plugin by kwebble?

  18. lukeMV says

    Any easy to understand guides on how to add options to the custom posts? For example, if a movie is drama, comedy, horror…. to have those options as check boxes WITHIN the custom post edit panel? I can’t seem to find a guide or plug-in for that.

  19. Paul says

    Hi, That was a great article. I was hoping that you may know the answer to my question.
    In the last couple of lines you have:

    query_posts(array('post_type' => array('post', 'movies')));

    this returns all posts and post_types named movies.

    Do you know how to return both post_types named ‘movies’ and posts in the category ‘movies’ but exclude all other posts that do not have this category??

    • Editorial Staff says

      Custom Post Types are good for users who are using WordPress for more than a Blog, for example CMS. Lets say if you want to have a site that has your portfolio and your blog. Obviously you don’t want your blogs to look the same way as your portfolio does. That is when custom post types comes in handy. This is a very versatile feature for taking WordPress to the next level. For average blog user, they probably don’t need custom post types.

      Administrador

      • Tracy B. says

        Okay, but I’m still trying to understand the difference between this and just categorizing things. I’ve made plenty of sites for people where separate pages do things like list only the “current events” category and another the “projects” category or whatever. How is this better?

  20. Chris says

    I can’t help but think that this would have been more useful if you showed something out of the ordinary with post types, rather than use the old “movies and books” bit.

    How about a sideblog using post types, or something a bit more practical? All this does is re-state what the WP Codex will eventually have, if it isn’t already on there.

    • Editorial Staff says

      We are sorry that you feel this way Chris. WP Codex will not have a video that will show you how to do this. It does not matter what names we use for the custom post types, the idea is how to add them. We will not create an extra-ordinary site just to write a post about custom post type. If you seek that knowledge, you are probably better off doing it yourself. This blog still has to fulfill the needs of the beginner level users hence why we shared the plugin method.

      Administrador

  21. Kevin Elliott says

    Will this work on WordPress 2.9 or is it only for 3.0?

    I tried using 3.0, but some quirk happened where none of my plugins would activate, even the ones that said they activated. Was very strange!

    -Kevin

      • Marc says

        Allright, I see, thnx! ;)

        Then I suppose you started the hard code way? At the time seeing all the coding stuff only, I just quit. Therefore didn’t see the plugin way I guess…

  22. Rilwis says

    Very nice article. The Custom Post Type UI plugin has the options very similar to raw PHP code of registering post types, that is great for developers.

    Thanks for introducing many useful plugin to work with custom post types.

  23. Bryan says

    I’m happy that WordPress has integrated custom post types right into the wp framework. However I’m not seeing how it is any better than using plugins already available such as Magic Fields or Flutter. With those plugins you get the same effect plus easy to setup custom fields with lots of different types and flexibility in how to enter and display your data. Does wp 3.0 support anything like that right out of the gate?

    • Editorial Staff says

      You can create a UI for custom fields and just about anything in the backend with Custom Post Types. You are right that those plugins make it very easy for users, but if any of those plugins fall on development, then you are left with no choice.

      Administrador

      • Bryan says

        Fair enough. I’ve played around with the beta a bit, but not as much as I should I suppose. It would be exciting if it did go more that direction. Since I’ve become experienced using those plugins I almost don’t make a site now with one

        So that would be great if all those tools were available and handled within the original application. I can see it leading to better backend management and encourage more people to contribute to it rather than a smaller group supporting a particular plugin.

        • Ian says

          I think they have intentionally left some of the custom post type code as code. To allow the average user to have to deal with it.

    • ravalde says

      I cant get any taxonomies to display in twentyeleven neither can I find a tutorial that shows me how from start to finish all seem to focus on twentyten and the loop

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.