Registering and Displaying WordPress Custom Post Types In a Very Easy Way

This post was moved to http://www.wpworking.com/category/custom-post-types-2/


In WordPress, you can define custom post types. It means that you can have on you wp-admin menu, more menu items, besides “Posts”, “Midia”, “Links”, “Pages”, etc, and work with your new post type as you do with the default menus, categorizing, adding content, etc.
No WordPress, você pode definir tipos de posts personalizados. Isso significa que você pode ter no seu menu do wp-admin, mais itens de menu além de “Posts”, “Mídia”, “Links”, “Páginas”, etc, e trabalhar com els como faz com os tipos padrão, categorizando, adicionando conteúdo, etc.

Let’s create a new custom post type. Open your functions.php file, on your theme directory, and paste the code bellow.
Vamos criar um novo tipo de post personalizado Abra seu arquivo functions.php, no diretório de seu tema, e cole o código abaixo.

// The register_post_type() function is not to be used before the 'init'.
add_action( 'init', 'videos_init' );

/* Here's how to create your customized labels */
function videos_init() {
	$labels = array(
		'name' => _x( 'Videos', 'custom post type generic name' ), // Tip: _x('') is used for localization
		'singular_name' => _x( 'Videos', 'individual custom post type name' ),
		'add_new' => _x( 'Add New', 'add' ),
		'add_new_item' => __( 'Add New Video' ),
		'edit_item' => __( 'Edit Video' ),
		'new_item' => __( 'New Video' ),
		'view_item' => __( 'View Video' ),
		'search_items' => __( 'Search Videos' ),
		'not_found' =>  __( 'No Video Found' ),
		'not_found_in_trash' => __( 'No Video Found in trash' ),
		'parent_item_colon' => ''
	);

	// Create an array for the $args
	$args = array( 'labels' => $labels, /* NOTICE: the $labels variable is used here... */
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
	); 

	register_post_type( 'video', $args ); /* Register it and move on */
}

Now you got a new menu on your wp-admin, called Videos. For further info about the register_post_type() function, visit the Codex.
Agora você tem um novo menu no seu wp-admin, chamado Videos. Para mais informações sobre a função register_post_type(), visite o Codex.

What about creating a category and a tag for this new Videos menu? Paste the code bellow on your functions.php
Que tal criar uma categoria e uma tag para este novo menu Videos? Cole o código abaixo em seu arquivo functions.php

// hook into the init action and call create_book_taxonomies() when it fires
add_action( 'init', 'create_video_taxonomies', 0 );

// create two taxonomies, genres and writers for the post type "videos"
function create_video_taxonomies() {

	// Add new taxonomy, make it hierarchical (like categories)
	$labels = array(
		'name' => _x( 'Genres', 'taxonomy general name' ),
		'singular_name' => _x( 'Genres', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search Genres' ),
		'all_items' => __( 'All Genres' ),
		'parent_item' => __( 'Main Genre' ),
		'parent_item_colon' => __( 'Main Genre:' ),
		'edit_item' => __( 'Edit Genre' ),
		'update_item' => __( 'Update Genre' ),
		'add_new_item' => __( 'Add Genre' ),
		'new_item_name' => __( 'New Genre Name' ),
	); 	

	register_taxonomy( 'genre', array( 'video' ), array(
		'hierarchical' => true,
		'labels' => $labels, /* NOTICE: Here is where the $labels variable is used */
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'genre' ),
	));
	// Add new taxonomy, NOT hierarchical (like tags)
	$labels = array(
		'name' => _x( 'Actor', 'Actor Name' ),
		'singular_name' => _x( 'Actor', 'Individual Actor Name' ),
		'search_items' =>  __( 'Search Actors' ),
		'popular_items' => __( 'Popular Actors' ),
		'all_items' => __( 'All Actors' ),
		'parent_item' => null,
		'parent_item_colon' => null,
		'edit_item' => __( 'Edit Actors' ),
		'update_item' => __( 'Update Actor' ),
		'add_new_item' => __( 'Add New Actor' ),
		'new_item_name' => __( 'New Actor Name' ),
		'separate_items_with_commas' => __( 'Separate Actors With Commas' ),
		'add_or_remove_items' => __( 'Add or Remove Actors' ),
		'choose_from_most_used' => __( 'Choose From Most Used Actors' )
	);
	register_taxonomy( 'actor', 'video', array(
		'hierarchical' => false,
		'labels' => $labels, /* NOTICE: the $labels variable here */
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'actor' ),
	));
} // End of create_video_taxonomies() function.

We’ve created two taxonomies for the custom post type video. Genre(hierarchical), works as a category. Actor(not hierarchical), works as a tag. For further info about the register_taxonomy() function, visit the Codex.
Nós criamos duas taxonomias para o tipo de post personalizado video. Genre(hierárquica), funciona como uma categoria. Actor(não hierárquica) funciona como uma tag. Para maiores informações sobre a função register_taxonomy() , visite o Codex.

So much hard working! Now let’s have fun🙂 , let’s display the posts.
Quanta trabalheira! Agora vamos nos divertir🙂 , vamos exibir os posts.

<?
// * if you want to work with the genre category on your query
// $wp_query = new WP_Query(array('post_type' => 'video', 'genre' => 'scifi','posts_per_page' => -1));
//
// * if you want to work with the actor tag on your query
// $wp_query = new WP_Query(array('post_type' => 'video', 'genre' => 'scifi','actor' => 'keanureaves','posts_per_page' => -1));
//
$wp_query = new WP_Query(array('post_type' => 'video', 'genre' => 'scifi','actor' => 'keanureaves','posts_per_page' => -1));
if (have_posts()) :
     while (have_posts()) : the_post();
?>
     <div>
       <h3><a href="<?the_permalink();?>"><?=get_the_title();?></a></h3>
     </div>
     <div>
       <p><?=get_the_content();?></p>
     </div>
<?
    endwhile;
else:
?>
     <div>
       <p>No registers found.</p>
     </div>
<?
endif;
?>

That’s all folks. Copy, past and make it work. The code above was tested a lot, please let me know about any issue.
Era isso pessoal. Copiem, colem e façam acontecer. O código acima foi bastante testado, por favor me mantenham informado sobre qualquer dificuldade.

,

  1. #1 by jake on March 3, 2011 - 5:34 am

    Great post! I was wondering if you could help me out. I have a WordPress site created for selling used boats. Basically, I want the functionality to search a custom post type for custom fields using a series of drop downs for users to narrow their search (e.g. boat manufacturer, year, location, etc.) I have the custom post type created and all of the custom fields, now I just need the search working. I’ve tried the “WP Custom Fields Search” plugin and it gets me 95% there – I just need it to search the custom post type.

    Is this something you think you can help me with?

    • #2 by Alvaro Neto on March 3, 2011 - 12:33 pm

      Hi Jake, I’ll take a look on it, I can promisse when I’ll answer cos I work on the blog in my free time, but I’ll take a look.

  2. #3 by ChrisDigital on March 25, 2011 - 8:05 pm

    This is a great post. Keep up the good work.

  3. #4 by Flávio Araújo on April 18, 2011 - 12:52 am

    Hi,
    i´m using something just like that. But when I click to add new “category” on post editing page, a blank field appears to type the name of the new category. But when I click to add, the new category does not show up. But refreshing the page, the new category appears. Someone know what cand be happening?

    Tks

    • #5 by Alvaro Neto on April 18, 2011 - 12:23 pm

      It’s hard to tell you what’s happening without taking a look on your code, or knowing the steps you took on your WordPress installation. Try to take a look on your custom post types registering code or maybe update your WordPress.

  4. #6 by Flávio Araújo on April 18, 2011 - 12:33 pm

    Hi,

    I´m found where is the error. I don´t know why, but is here.😛

    I was using this function to create a pagination without plugin:

    http://wordpressapi.com/2010/12/08/wordpress-pagination-style-wordpress-plugin/

    So I started a new instaltion and one by one, I commented some functions. When I disableled this function, everything worked fine.

    So, I recomend to use one of the function below to create pagination without plugin.

    http://design.sparklette.net/teaches/how-to-add-wordpress-pagination-without-a-plugin/

    http://www.kriesi.at/archives/how-to-build-a-wordpress-post-pagination-without-plugin

    As I sad, I don´t know the reason, but here is the tip😉

    Best regards.

    Flávio

    • #7 by Alvaro Neto on April 18, 2011 - 1:09 pm

      Great to know it works. Thank you for your tip. Best regards.

  5. #8 by Jared Ilyas on April 29, 2011 - 10:20 pm

    For those of you getting sick of the default WordPress editor, there is a list of more than a dozen WordPress Editors at http://bloggerkhan.com/what-is-the-best-editor-for-wordpress/33

    I have started experimenting with two. Let’s see.

    • #9 by Alvaro Neto on April 29, 2011 - 10:39 pm

      Hey Jared, thanks for the tip. Best regards!

  6. #10 by racerex on June 21, 2011 - 3:34 am

    I came across your post which is right up my alley! I am trying to display movies from a custom post type on a page and can’t seem to get it to work but am close! I would be so grateful for any insight!

    So I have a custom post type called “Movies”
    in that custom post type I have two categories: “Now Showing”, and “Coming Soon”

    Right now the code is bringing in ALL of the posts from the custom post type, and I would like to bring them in by category. Here is the code:

    Coming Soon Movies

    ‘movies’, ‘paged’=>$paged );
    $loop = new WP_Query( $args );
    $i = 1;

    while ( $loop->have_posts() ) : $loop->the_post(); ?>

    How can I do what I am after??????

    • #11 by Alvaro Neto on July 4, 2011 - 1:44 pm

      Hi there my friend, it’s not even close to an elegant solution, but you can try something like this:

      $querycp = array( ‘post_type’=>’Movies’,’posts_per_page’ => -1 );
      query_posts($querycp);
      while (have_posts()) : the_post();
      $terms = get_the_terms(get_the_ID(), ‘cases_cat’);
      foreach ( $terms as $term ) {
      $catref = $term->slug;
      }
      if($catref==”Coming Soon”):
      echo get_the_title();
      endif;
      endwhile;

  7. #12 by racerex on June 21, 2011 - 3:37 am

    For some reason the code did not make it through….

    • #13 by Alvaro Neto on July 4, 2011 - 1:45 pm

      Check the answer for your first comment, please

  8. #14 by Felipe Caroé on August 16, 2011 - 2:46 am

    Man, thank you very much!
    I’ve used it and it works pretty fine!

    That’s exactly why I have just donated one beer for you!

    Anytime you need, just ask me🙂

    HUGZ!

    • #15 by Alvaro Neto on August 16, 2011 - 4:36 am

      Thank you brother, you presented me WP, so I’m very happy to read you comment. May the force be with us.

  9. #16 by Alvaro Neto on March 25, 2011 - 7:53 pm

    Thanks for linking! I’ve got very happy with it! It’s a great reward for my work. Best Regards.

  1. Displaying Info From a Specific Custom Taxonomy Term(Hierarchical Taxonomies) On WordPress « It works on WordPress
  2. Intro to WordPress Plugin Development : NYC Meetup Recap : ChrisDigital.com : Digital Designer Blog
  3. WordPress Custom Taxonomy Page Example – Displaying Custom Post Types Posts « It works on WordPress
  4. Retrieving The Total Number of Posts from a Specific Custom Post Type WordPress Taxonomy « It works on WordPress
  5. Intro to WordPress Plugin Development : NYC Meetup Recap : ChrisDigital.com : Digital Designer Blog | Build a Website
  6. WordPress WordPress Custom Taxonomy Page Example with Taxonomy Selection Function(select field) « It works on WordPress
  7. It works on WordPress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: