Custom Post Types: How to create custom blog types in WordPress

How to remove Query Strings from JavaScript and CSS in WordPress
What is PHP? – Basic PHP Programming Guide

In this tutorial, we will create a plugin to add two new types of post in WordPress, known as Custom Post Types . And then we will create new layouts for these new types of WordPress posts using templates. You can check out this article How to create WordPress plugins  if you need a refresher on the subject. You will also learn how to enable the Custom Fields for each WordPress post, and display these fields in the new templates.

At the end of the article How to Create Custom Posts Types, you will notice that the custom post types WordPress provide full control on how the content will be displayed to your visitors. If you write posts copyright, you can only create a layout for them. Also if you write reviews of movies and music, you can add areas for extra content and make these reviews do not appear as posts from your blog.

But before we begin, let’s find out what are types of custom posts Custom Post Types WordPress.

What is Type Custom Post?

In short, the type of custom WordPress post, translation Custom Post Types , allows you to sort your posts based on the content of each of them. In WordPress, the types of post are standard Posts, Pages, Files, etc.

Generally, you write all your posts in the section Posts Administrator Control Panel, then select the category for each post. All posts will be displayed in the same list, making it difficult to differentiate by type of content that contains the posts.

The types of custom posts have their own links in the admin control panel. Posts created in this way can be categorized as a normal post, then you will have complete freedom to sort and display these posts the way you want.List of types of standard WordPress post

Let’s make it clear that we use for configuration in English, we will proceed with the prints of this tutorial in English, always referencing movies for movies and reviews for evaluations, okay? If you have any questions during the process, leave a comment that will help you.

In the above example, if a user access to movie database section on your site, posts evaluations will not be included. If you do, for example, the categories “Action” and “Romance”, users can access the page of the category “Action” and read all the reviews and films related to this category.

When creating a new type of post, you have several options as where the link will be displayed on the Admin menu, if the new types of posts are included in the search results, if accepted quotes, comments are allowed, and so on.

You can also change various parts of the text (set using the array $ labels ), rename Add New Posts (add new posts)  to Add New Movies (add new movies) . For example, you can rename the text ” feature image ” (standard image) to  Add Poster (Poster add) .

You can also choose to activate the custom fields feature posts editor, which is hidden by default and must be enabled using the link  Screen Options at the top of the editor.

Following the example of the Movies and Reviews, a post Movies can add custom fields as a release annual, director, rating IMDB, and so on, with synopses of the films and the content of the posts.Custom Fields WordPress

Generally, any custom fields you create can be selected in all other types of posts, then a plugin to limit where each of these fields are displayed is accurate.

Creating New Types of Posts

With all the significant changes of WordPress, create a plugin is strongly recommended. You can also create a custom post type of the file functions.php of a theme. In this tutorial, we will create a plugin and continue using the example database / reviews,  ok?

To create a custom post type, you must write a new function that calls the WordPress function named register_post_type () with two parameters. Its function must be connected to action hook init , otherwise your custom post type will not be registered correctly.

  1. // The custom function MUST be hooked to the init action hook
  2. add_action ( init , ‘lc_register_movie_post_type’ ) ;
  3. // The custom function calls que register_post_type
  4. function lc_register_movie_post_type ( ) {
  5. // Set various pieces of text, $ labels is used inside the $ args array
  6. $ labels = array (
  7. ‘name’ => _x ( ‘Movies’ , ‘ post general type name ” ) ,
  8. ‘singular_name’ => _x ( ‘Movie’ , ‘post type singular name’ ) ,
  9. ) ;
  10. // Set various pieces of information about the post type
  11. $ args = array (
  12. ‘labels’ => $ labels,
  13. ‘description’ => ‘My custom post type’ ,
  14. ‘public’ => true,
  15. ) ;
  16. // Register the movie post type with all the information contained in the $ arguments array
  17. register_post_type ( ‘movie’ , $ args ) ;
  18. }
// The custom function MUST be hooked to the init action hook
add_action (init, 'lc_register_movie_post_type');

// The custom function calls que register_post_type
lc_register_movie_post_type function () {

  // Set various pieces of text, $ labels is used inside the $ args array
  $ Labels = array (
     'Name' => _x ( 'Movies', 'post general type name'),
     'Singular_name' => _x ( 'Movie', 'post type singular name'),
     ...
  );

  // Set various pieces of information about the post type
  $ Args = array (
    'Labels' => $ labels,
    'Description' => 'My custom post type'
    'Public' => true,
    ...
  );

  // Register the movie post type with all the information contained in the $ arguments array
  register_post_type ( 'movie', $ args);
}

All custom functions must be prefixed to avoid conflicts when using other plugins or other theme functions. Here we will randomly use the LC letters, just as an example.

The two parameters register_post_type () are:

  1. The name of the type of post, maximum of 20 characters and can not contain spaces or capital letters.
  2. An array associative named $ args that contains key information about the types of post in pairs ‘key’ => ‘value’ .

As the arguments and the label are arrays is clearer to write the first label in its own variable, then the variable $ args, and only then call the function.

The $ args Array

The keys commonly used for the array $ args are listed below and are all optional:

  • labels – An array that defines various parts of the text, for example “Add new post” can be renamed to “Add new movie.” The keys to the labels array will be explained in the list below.
  • description – a short, descriptive summary of the type of post, this can be displayed in the templates of the types of posts but do not appear anywhere else.
  • public – the types of posts are visible to authors and visitors, the default value is FALSE, and means that will not appear in the Administrator Control Panel.
  • exclude_from_search – if the posts of these types usually appear in the search results. The default value is the opposite of the value of the public.
  • publicly_queryable – if such posts can be retrieved using the URL as http://www.mywebsite.com/?post_type=movie or in enhanced mode via query_posts () function. The default value is the public value.
  • show_ui – the menu links and the editor of posts will be visible in the Administrator Control Panel. The default value is the public value.
  • show_in_nav_menus – if the posts of this type can be added to menu navigation screen created via Appearance> Menus. The default value is the public value.
  • show_in_menu – where the link of the types of posts will appear in the navigation in the admin control panel. FALSE hides the link. TRUE adds the link as a new top – level link. Enter a string allows you to place the link to exist sublink the top – level link, ie typing options-general.php , will be applied under the Settings link .
  • Show_in_admin_bar – the type of posts will appear at the top of the Admin bar below the link + again.
  • Menu_position – the new link in the navigation position Administrator Control Panel, 5 puts it below the posts, 100 places it under Settings, visit the WordPress Codex entry for a complete list of positions.
  • Hierarchical – if the posts can be assigned to a post Parent, if it is TRUE, the array $ support must contain the feature ‘page-attributes’.
  • supports – enables selectively several features of posts, as featured images, quotes, custom fields, etc. If set to FALSE instead of array , disable the editor for this type of post – this is very useful if you want to block all posts such as the visible remains (list of values arrays, are below).
  • Taxonomies – An array taxonomies that can be applied to such posts, taxonomies must already be registered – this does not create them.
  • Has_archive the type of post has an archive page, the URL follows the structure of the permalink, and the slug is the name that you enter in the parameter 1 register_post_types (), ie http://www.mysite.com / movies_reviews / shows all posts movies_reviews.
  • query_var  – TRUE or FALSE defines whether the post can be viewed by entering the type of post and post the name to refer to the url, ie ‘http://www.mysite.com/? Movie = matrix ‘. If you type a string of text, you can set the text to be used after the character ? Then typing ‘movie’ result in ‘? movie = matrix ‘ .

This complete list can be viewed on the WordPress Codex page for register_post_type () .

The labels Array

The first key in the array $ arg is named labels and should be an array . This defines various parts of the text related to this post. As it contains a lot of information, it is better to create a variable named $ labels to store it. The sample code above makes this clear.

Below are some important keys to the labels arrays , all are optional.

  • name – the general name for the type of post, for example: movies.
  • singular_name – to name a single post of this type, for example: movies.
  • add_new – replaces the text ‘Add New’ by ‘Add Movie’, for example.
  • add_new_item – replaces the text ‘Add New Post’ by ‘Add New Movie’
  • edit_item – Replaces ‘Edit Post’ by ‘Edit Movie’.
  • featured_image – Replaces ‘Feature Image’ in the editor by ‘Movie Post’
  • set_featured_image – Replaces ‘Feature Sets Image’ by ‘Add Movie Poster’, for example.
  • MENU_NAME – Change the text of the top – level link, the default text and the name of the key.

See the complete list in the WordPress Codex page for register_post_type () .

The ‘supports’ Array

// Enable specific features in the post editor for my post type
$ Supports = array ( 'title', 'editor', 'author', 'thumbnail');

// Disable ALL features of the post editor for my post type
$ Supports = FALSE;

One of the keys in the array $ args is named supports . This is an array simple where you write the list of custom posts editor features. By default, only the title and the publisher are enabled.

You can also write FALSE rather than an array , to disable all editing features of posts, including title and content. This means that posts can not be edited, but still quite visible.

Here is a list of features of post editors that you can enable in the array $ supports :

  • Title (title);
  • Editor;
  • Author – (Author) NOTE: This feature allows you to change the author of the post;
  • Thumbnail (thumbnail);
  • Excerpt (abstract);
  • trackbacks;
  • Custom-fields (custom fields);
  • Comments (comments);
  • Revisions (revisions);
  • Page-attributes (page attributes);
  • Post-formats (the posts format).

Create New Types of Post via Plugin

Now that we know what information is needed for a function, we can create our own plugin, write custom functions, and connect them to the hook init .

  1. <? Php
  2. / *
  3. Plugin Name: My Custom Post Types
  4. Description: Add post types for movies and movie reviews
  5. Author: Liam Carberry
  6. * /
  7. Hook // <strong> lc_custom_post_movie () </ strong> to the action hook init
  8. add_action ( init , ‘lc_custom_post_movie’ ) ;
  9. // The custom function to register a movie post type
  10. function lc_custom_post_movie ( ) {
  11. // Set the labels, this variable is used in the $ args array
  12. $ labels = array (
  13. ‘name’ => __ ( ‘Movies’ ) ,
  14. ‘singular_name’ => __ ( ‘Movie’ ) ,
  15. ‘add_new’ => __ ( ‘Add New Movie’ ) ,
  16. ‘add_new_item’ => __ ( ‘Add New Movie’ ) ,
  17. ‘edit_item’ => __ ( ‘Edit Movie’ ) ,
  18. ‘NEW_ITEM’ => __ ( ‘New Movie’ ) ,
  19. ‘all_items’ => __ ( ‘All Movies’ ) ,
  20. ‘view_item’ => __ ( ‘View Movie’ ) ,
  21. ‘search_items’ => __ ( ‘Search Movies’ ) ,
  22. ‘featured_image’ => ‘Poster’ ,
  23. ‘set_featured_image’ => ‘Add Poster’
  24. ) ;
  25. // The arguments for our post type, to be entered the parameter of register_post_type 2 ()
  26. $ args = array (
  27. ‘labels’ => $ labels,
  28. ‘description’ => ‘Holds our movies and movie specific date’ ,
  29. ‘public’ => true,
  30. ‘menu_position’ => 5 ,
  31. ‘supports’ => array ( ‘title’ , ‘editor’ , ‘thumbnail’ , ‘excerpt’ , ‘comments’ , ‘custom-fields’ ) ,
  32. ‘has_archive’ => true,
  33. ‘show_in_admin_bar’ => true,
  34. ‘show_in_nav_menus’ => true,
  35. ‘has_archive’ => true,
  36. ‘query_var’ => ‘film’
  37. ) ;
  38. // Call the current WordPress function
  39. // Parameter 1 is a name for the entry type
  40. // Parameter 2 is the array $ args
  41. register_post_type ( ‘movie’ , $ args ) ;
  42. }
  43. Hook // <strong> lc_custom_post_movie_reviews () </ strong> to the action hook init
  44. add_action ( init , ‘lc_custom_post_movie_reviews’ ) ;
  45. // The custom function to register a movie review post type
  46. function lc_custom_post_movie_reviews ( ) {
  47. // Set the labels, this variable is used in the $ args array
  48. $ labels = array (
  49. ‘name’ => __ ( ‘Movie Reviews’ ) ,
  50. ‘singular_name’ => __ ( ‘Movie Review’ ) ,
  51. ‘add_new’ => __ ( ‘Add New Movie Review’ ) ,
  52. ‘add_new_item’ => __ ( ‘Add New Movie Review’ ) ,
  53. ‘edit_item’ => __ ( ‘Edit Movie Review’ ) ,
  54. ‘NEW_ITEM’ => __ ( ‘New Movie Review’ ) ,
  55. ‘all_items’ => __ ( ‘All Movie Reviews’ ) ,
  56. ‘view_item’ => __ ( ‘View Movie Reviews’ ) ,
  57. ‘search_items’ => __ ( ‘Search Movie Reviews’ )
  58. ) ;
  59. // The arguments for our post type, to be entered the parameter of register_post_type 2 ()
  60. $ args = array (
  61. ‘labels’ => $ labels,
  62. ‘description’ => ‘Holds our movie reviews’ ,
  63. ‘public’ => true,
  64. ‘menu_position’ => 6 ,
  65. ‘supports’ => array ( ‘title’ , ‘editor’ , ‘thumbnail’ , ‘excerpt’ , ‘comments’ , ‘custom-fields’ ) ,
  66. ‘has_archive’ => true,
  67. ‘show_in_admin_bar’ => true,
  68. ‘show_in_nav_menus’ => true,
  69. ‘has_archive’ => true
  70. ) ;
  71. // Call the current WordPress function
  72. // Parameter 1 is a name for the entry type
  73. // $ args array goes in parameter 2.
  74. register_post_type ( ‘review’ , $ args ) ;
  75. }
<? Php
/ *
Plugin Name: My Custom Post Types
Description: Add post types for movies and movie reviews
Author: Liam Carberry
* /
 
Hook // <strong> lc_custom_post_movie () </ strong> to the action hook init
add_action (init, 'lc_custom_post_movie');
 
// The custom function to register a movie post type
lc_custom_post_movie function () {
 
  // Set the labels, this variable is used in the $ args array
  $ Labels = array (
    'Name' => __ ( 'Movies'),
    'Singular_name' => __ ( 'Movie'),
    'Add_new' => __ ( 'Add New Movie'),
    'Add_new_item' => __ ( 'Add New Movie'),
    'Edit_item' => __ ( 'Edit Movie'),
    'NEW_ITEM' => __ ( 'New Movie'),
    'All_items' => __ ( 'All Movies'),
    'View_item' => __ ( 'View Movie'),
    'Search_items' => __ ( 'Search Movies'),
    'Featured_image' => 'Poster'
    'Set_featured_image' => 'Add Poster'
  );
 
  // The arguments for our post type, to be entered the parameter of register_post_type 2 ()
  $ Args = array (
    'Labels' => $ labels,
    'Description' => 'Holds our movies and movie specific date'
    'Public' => true,
    'Menu_position' => 5,
    'Supports' => array ( 'title', 'editor', 'thumbnail', 'excerpt', 'comments', 'custom-fields'),
    'Has_archive' => true,
    'Show_in_admin_bar' => true,
    'Show_in_nav_menus' => true,
    'Has_archive' => true,
    'Query_var' => 'film'
  );
 
  // Call the current WordPress function
  // Parameter 1 is a name for the entry type
  // Parameter 2 is the array $ args
  register_post_type ( 'movie', $ args);
}
 
Hook // <strong> lc_custom_post_movie_reviews () </ strong> to the action hook init
add_action (init, 'lc_custom_post_movie_reviews');
 
// The custom function to register a movie review post type
lc_custom_post_movie_reviews function () {
 
  // Set the labels, this variable is used in the $ args array
  $ Labels = array (
    'Name' => __ ( 'Movie Reviews'),
    'Singular_name' => __ ( 'Movie Review'),
    'Add_new' => __ ( 'Add New Movie Review'),
    'Add_new_item' => __ ( 'Add New Movie Review'),
    'Edit_item' => __ ( 'Edit Movie Review'),
    'NEW_ITEM' => __ ( 'New Movie Review'),
    'All_items' => __ ( 'All Movie Reviews'),
    'View_item' => __ ( 'View Movie Reviews'),
    'Search_items' => __ ( 'Search Movie Reviews')
  );
 
  // The arguments for our post type, to be entered the parameter of register_post_type 2 ()
  $ Args = array (
    'Labels' => $ labels,
    'Description' => 'Holds our movie reviews'
    'Public' => true,
    'Menu_position' => 6
    'Supports' => array ( 'title', 'editor', 'thumbnail', 'excerpt', 'comments', 'custom-fields'),
    'Has_archive' => true,
    'Show_in_admin_bar' => true,
    'Show_in_nav_menus' => true,
    'Has_archive' => true
  );
 
  // Call the current WordPress function
  // Parameter 1 is a name for the entry type
  // $ args array goes in parameter 2.
  register_post_type ( 'review', $ args);
}

If you enable this plugin, you should now see two new links in the navigation Administrator Control Panel, just below the link posts.

When you mouse over the sub -links , you will see “View All” and “Add new”, the text will be set in array $ labels . Check your editor and see that the labels have changed.

Limiting Custom Fields to the Specific Post Type

When you add a custom field to a post, this field remains already saved and then you can quickly add it to any post. Custom fields that you add will appear in a drop-down list in each post.

This can make finding the fields you need in specific types of posts. If you want to limit the custom fields to be available only in certain types of posts, the easiest way is to use a plugin.

The advanced custom fields plugin adds a simple editor to WordPress that allows you to create custom fields and set only to appear in their types of post.

You can define what type of input each field, such as text box, text area, email address, etc., or something more advanced like embedar Google Maps, with which you can select a location to highlight and display in their posts.Drop-down menu of the types of post

You can also define where on the screen editor, the custom fields are displayed. As these fields are created via plugin, you should use the function of this plugin to display them. This will be explained in the next section.

Styling New Types of Posts

Themes to create templates for their types of posts, you need only have to create files within the main theme of your directory with the correct names. If you do not create templates, WordPress will use single.php and archive.php in place, keeping all your posts and identical files.

  • Template for a single entry – single – post-type} {php
  • Template for an archive page – archive- {post-type} .php .

Part {} post-type file names should be the parameter name 1 of register_post_type () .

  • For our type of post Movie, the file names are single-movie.php and archive-movie.php .
  • For our kind of post Review, the file names are single-review.html and archive-review.html .

The best way to start is doubling single.php or archive.php and rename them as above. This means that overall, the structure is identical to the theme of the rest, and all of the tags necessary templates are already in place.

Displaying Custom Fields in Posts

To display custom fields created in the default WordPress editor, you can use two functions.

  1. // Generates all custom fields attached to the post in a <ul> list
  2. the_meta ( ) ;
  3. // Get a specific piece of information
  4. echo get_post_meta ( $ post-> ID, ‘Budget’ , TRUE ) ;
// Generates all custom fields attached to the post in a <ul> list
the_meta ();

// Get a specific piece of information
echo get_post_meta ($ post-> ID, 'Budget', TRUE);

These functions should be in the archives of templates used to display your posts.

the_meta ()

Displays all the custom fields attached to the post in the <ul> list. The end tag <ul> will look like this:

  1. <ul class = ‘post-meta’ >
  2. <Li>
  3. <span class = ‘post-meta-key’ > { your_key } </ span> { your_value }
  4. </ Li>
  5. </ Ul>
<Ul class = 'post-meta'>
  <Li>
    <Span class = 'post-meta-key'> {your_key} </ span>} {your_value
  </ Li>
</ Ul>

This works anywhere from a single post template, but if you are exhibiting elsewhere, should be inserted in the loop WordPress .

get_post_meta ()

  • 3 uses parameters and returns a result.
  • The first parameter is the post ID, you can use here the $ post-> ID to get the current post ID.
  • The second parameter is the name of the custom field, and is case-sensitive .
  • The third parameter is a boolean named $ single and can be TRUE (returns the result as a string) or FALSE (returns an array ).

NOTE: You can create multiple custom fields with the same name and different values. If there is multiple fields with the same name by setting FALSE returns an array of all of them.

  1. <? Php
  2. $ movie_box_art = get_post_meta ( $ post-> ID, “Box Art ‘ , TRUE ) ;
  3. if ( ! empty ( $ movie_box_art ) ) { ?>
  4. <div class = “movie-poster-box” >
  5. <img src = “<? php echo $ movie_poster>?” alt = “<? php single_post_title (); ?> ” >
  6. </ Div>
  7. <? } ?>
<? Php
  $ Movie_box_art = get_post_meta ($ post-> ID, "Box Art ', TRUE);

if (! empty ($ movie_box_art)) {?>
  <Div class = "movie-poster-box">
    <Img src = "<? Php echo $ movie_poster>?" ​​Alt = "<? Php single_post_title ();?>">
  </ Div>
<? }?>

Since the function get_post_meta () returns a value, you can use the value in a conditional statement to change the layout properly.

In the above example, we looked at whether ‘movie’ is an art box attached to it via a custom field. If $ movie_box_art is not empty, copy the div and image.

Displaying Custom Fields Advanced

// Display field value
the_field ( 'Field Name');

// Return value field
get_field ( 'Field Name');

Advanced Custom Fields plugin provides its own function and shortcodes to display the fields.custom fields plugin wordpress

the_field ( ‘Field Name’);

Displays the value of the specific field, and you must use the Field name you entered when you created the Fields group.

get_field ( ‘Field Name’);

Returns the value of the specific field, useful for conditional statements.

These are the functions you should use more often. But there are more advanced functions and you can check them in the Official Document .

shortcode

[ACF field = "Field Name"]

You can display the fields directly into a post using the shortcode above.

Displaying Custom Posts Types at Home

  1. / Hook our custom function to the pre_get_posts action hook
  2. add_action ( ‘pre_get_posts’ , ‘add_reviews_to_frontpage’ ) ;
  3. // Alter the main query
  4. function add_reviews_to_frontpage ( $ query ) {
  5. if ( is_home ( ) && $ query-> is_main_query ( ) ) {
  6. $ query-> September ( ‘post_type’ , array ( ‘post’ , ‘movie’ , ‘review’ ) ) ;
  7. }
  8. return $ query;
  9. }
/ Hook our custom function to the pre_get_posts action hook
add_action ( 'pre_get_posts' 'add_reviews_to_frontpage');
 
// Alter the main query
add_reviews_to_frontpage function ($ query) {
    if (is_home () && $ query-> is_main_query ()) {
        $ Query-> set ( 'post_type', array ( 'post', 'movie', 'review'));
    }
    return $ query;
}

By default, custom types of posts are not displayed on the homepage, then you have to write a new function that calls the method September WordPress’ WP_Query .

The function checks if the visitor is on the Top Page and if the query active is the main generated by WordPress.

$ query-> set () takes two parameters:

  • The first parameter is the property you want to change, in this case we intend to want to change ownership post_type .
  • The second parameter is the array you want as property value post_type.

In the above, the array starts with ‘post’ – this is because each post in WordPress is a type of post ‘post’, and we want to include them on the homepage.

If you want to customize the posts of a particular type on the homepage, you can remove the type ‘posts’ and apply only your type of personalized post. We added ‘movie’ and ‘review’ in the array , then the homepage now displays regular posts, all posts and movies all posts assessments.

The amount you enter must be the name used in parameter 1 function register_post_type () .

Conclusion

Completion creating kind of wordpress post

In this tutorial you learned how to create custom types of posts  ( custom post types) , and the information that you need to do this. The flexibility that a type of personalized post provides makes it an essential resource for any site developed in WordPress.

When aligned with categories and taxonomies, you have full control of how your users view your posts.