Setting post type custom article types in wordpress tutorial _php instance

Source: Internet
Author: User

What is a custom post?
don't take it for granted that post is just a blog article, it is just an article class agent Word, even you can think it is content.
The custom model is not a very standard what rules, the article model can be any one of the content model you want, take WordPress itself is built in the following several content article model:

    • Blog posts
    • Page
    • Attachment
    • Correction
    • Navigation and other

You can understand this: it's just a flexible form of content that we use to create, edit, and store data, as we do with blog posts.

But here I still need to remind, the blog built-in post or a little bit different, you can use it to contain categories, tags, etc. to identify the content!
Why do you want to customize the article model?
WordPress has already provided some perfect default article models and applies to most sites, but we still need more options. I have enumerated some of the possible useful content models I have come up with and linked them to the corresponding examples.

    • List of real Estate
    • Active calendar (I know a lot of people are interested in this)
    • Video Data base
    • Book Database
    • No forum system with many integration issues
    • A ticketing system similar to the WordPress TRAC
    • Design albums or collections

You can also think of more content models than I enumerate. And I also want to learn more about the forum and the ticketing system in the future. These two systems I have achieved and want to get some feedback.

Create a Post Type
creating a new Post Type needs to be registered with the Register_post_type function. Need to cut down on your subject's functions.php file with this function:

Register_post_type ($post _type, $args);

$post _type parameter is the name of your custom post type, and the post type can be customized to a lot of functions, so the $args parameters in this function are many. So it is usually registered in the following format:

function My_custom_post_product () {
  $args = array ();
  Register_post_type (' product ', $args); 
Add_action (' init ', ' my_custom_post_product ');

Wrap in a function, define an array, and then attach to the action of Init. So WordPress will perform this function to register a custom post Type when initializing, because when calling Register_post_type (), you must precede the Admin_menu action in After_setup_ After the theme action, it's best to attach to the init action.
A lot of parameters, in order to write tutorials convenient, only listed more commonly used parameters, the overall structure is as follows:

 function My_custom_post_movie () {$labels = array (' name ' => _x (' Movies ', ' Post Typ E name '), ' Singular_name ' => _x (' Movie ', ' Post type single item name, because English has plural '), ' add_new ' => _x (' new movie ', ' Add New Content Link name '), ' Add_new_item ' => __ (' new movie '), ' Edit_item ' => __ (' edit movie '), ' New_item ' => __ (' New film '), ' All_items ' => __ (' All films '), ' View_item ' => __ (' View movie '), ' Search_items ' => __ (' Search for movie ') , ' Not_found ' => __ (' not found about the movie '), ' Not_found_in_trash ' => __ (' No related movie in the Recycle Bin '), ' Parent_item_colon ' =>
 ', ' menu_name ' => ' Movies '); $args = Array (' labels ' => $labels, ' description ' => ' movie Information for our website ', ' public ' => true, ' menu_position ' => 5, ' supports ' => Array (' title ', ' editor ', ' thumbnail ', ' excerpt ', ' comments '), ' has_archive ' => tru
Register_post_type (' movie ', $args);
} add_action (' init ', ' My_custom_post_movie '); 

Here for intuitive convenience, I directly use the Chinese, better should be in English and then through the localization function to translate into Chinese.
There are a lot of parameters, you can also use the GENERATEWP tool to customize the parameters, and then change, it will be a little easier.
From the code above, you can see that there is a labels configuration item in the $args array, which is used to configure the contents of the display copy, and to create an array separately for clarity. Other configuration Items read English can also guess the general meaning, if you want to learn more, you can look at the official document: Register_post_type.
Add the above code to the bottom of the theme functions.php and you'll find the Movies option in the background, which means the registration is successful:

At this time we can create a new Movie to publish a movie type article. But this is essentially the same as the article type, and we need more customization to refine our Movie type.
to add a classification function to the Post Type
in the movies, it can be divided into sci-fi, action, war and other categories, then we will add the classification function for the custom Movie, so that we can edit the new classification and classify our movies. This classification is the same as the nature of the classification in the article.
Adding a taxonomy requires the use of function register_taxonomy, which is also simple to use, similar to the registered post type function, except that a single parameter is used to specify the corresponding post type:

Register_taxonomy ($taxonomy, $object _type, $args);

For the purposes of this example, you can configure the following common parameters:

function My_taxonomies_movie () {
 $labels = array (
  ' name '       => _x (' movie classification ', ' Taxonomy name '),
  ' Singular_ Name '   => _x (' movie category ', ' taxonomy singular name '),
  ' Search_items '   => __ (' Search movie category '),
  ' All_items '     => _ _ (' All film categories '),
  ' Parent_item '    => __ (' The classification of the higher class of the film '),
  ' Parent_item_colon ' => __ (' The category of the superior of the film Classification: '), c13/> ' Edit_item '     => __ (' Edit the movie category '),
  ' Update_item '    => __ (' Update movie classification '),
  ' add_new_item '   = > (' Add new movie category '),
  ' New_item_name '   => __ (' new film Classification '),
  ' Menu_name '     => __ (' film Classification ')
 $args = Array (
  ' labels ' => $labels,
  ' hierarchical ' => true,
 Register_taxonomy (' movie_category ', ' movie ', $args);
Add_action (' init ', ' My_taxonomies_movie ', 0);

After adding to the topic, we see the familiar article classification function, but the above copy all become our custom content:

Here we add two categories as demos.
Add custom Meta Box to post Type
the type of movie we want to add is not just the body content, we also need to add some additional director and so on content. Then you need to add custom Meta box,meta box to add a custom form to the post page, write the article and fill in additional information and call it on the front end.
Custom Meta Box needs to use the Add_meta_box function:

Add_meta_box ($id, $title, $callback, $post _type, $context, $priority, $callback _args);

The old rules, the specific parameters of the content to view the official document, here only the common usage. We sign up for a Meta Box:

Add_action (' add_meta_boxes ', ' movie_director ');
function Movie_director () {
  add_meta_box (
    ' movie_director ',
    ' film director ',
    ' Movie_director_meta_box ',
    ' movie ',
    ' side ', ' Low

Then you specify the callback function in the configuration parameter movie_director_meta_box, we need to create the form inside the function:

function Movie_director_meta_box ($post) {
  //create temporary hidden form for security
  Wp_nonce_field (' Movie_director_meta_box ', ' Movie_director_meta_box_nonce ');
  Gets the previously stored value
  $value = Get_post_meta ($post->id, ' _movie_director ', true);
  ? >
  <label for= "Movie_director" ></label>
  <input type= "text" id= "Movie_director" Name= " Movie_director "value=" <?php Echo esc_attr ($value);?> "Placeholder=" enter director name >

This allows you to display the form you just created in the sidebar of the article interface:

But this time, your form is not available, because after you submitted the article did not save the contents of this Meta Box, the following is to verify the content of the code:

Add_action (' Save_post ', ' Movie_director_save_meta_box ');
function Movie_director_save_meta_box ($post _id) {
  //Security Checks/
  checks whether a one-time hidden form content is sent (to determine if a third party simulated submission) if
  (! Isset) ( $_post[' Movie_director_meta_box_nonce ']) {return
  Determine if the value of the hidden form is the same as before
  (! wp_verify_nonce ($_post[' movie_director_meta_box_nonce '), ' Movie_director_meta_box ') { return
  Determine if the user has permission if
  (! Current_user_can (' Edit_post ', $post _id)) {return
  Determine if the Meta Box is an empty
  if (! isset ($_post[' Movie_director ')) {return
  $movie _director = Sanitize_text_field ($_post[' movie_director '));
  Update_post_meta ($post _id, ' _movie_director ', $movie _director);

Although the most critical function is in the last sentence, be sure to pay attention to the safe checksum. After adding the code to the functions.php file, your Meta Box will work. If you need more forms, follow this pattern to customize the form structure, and then add the Save function.
Below, we can't wait to add two movie "Fish and Pot War: Destiny Duel" and "Fish and pot War: I love boiled fish" contents are as follows:

After adding, we can look at all the movies:

The list is empty, so ugly, can I add the Director field? Of course, you can use [manage $post type posts custom column] ($post_ Type_posts_custom_column) can be achieved, we add:

Add_action ("Manage_posts_custom_column", "Movie_custom_columns");
Add_filter ("Manage_edit-movie_columns", "Movie_edit_columns");
function Movie_custom_columns ($column) {
  global $post;
  Switch ($column) {case
      Echo Get_post_meta ($post->id, ' _movie_director ', true);
function Movie_edit_columns ($columns) {
  $columns [' movie_director '] = ' director ';
  return $columns;

The Column Director field is added and read from every article. So our list becomes:

OK, our back end part is so happy to finish. Open the Build good link look, eh, not Found? Yes, if your site has a fixed connection, when you create a new Post Type, you have to update the fixed connection settings in the background. Find the background fixed connection, and then click "Save Settings" below, you will be able to access the normal.
Show the contents of the Post Type
simply creating the post type simply allows you to enter the content, which makes no sense, and we also need to output the contents of the custom post type in the foreground.
Customizing the template and style for post Type
According to WordPress template call rules we can tell that we just need to create archive-[post_type].php and single-[post_type].php to implement the list customization and article customization of the Post type. These templates are called for rendering when accessing Post type,wordpress.
Note that you need to set the ' has_archive ' => true to have a list when registering the Post Type.
Now we're going to make a copy of the archive.php and single.php files in the theme, named Archive-movie.php and Single-movie.php, to illustrate, I don't do a lot of customization here, just output director information.
We output Meta Box information in the appropriate location near l.56 and L.23, respectively:

Echo ' Director: '. Get_post_meta (get_the_id (), ' _movie_director ', true);

Then refresh the access to the movie list and the specific movie to see the output of the director information.
Here just for example, in practice will often customize the structure and output of the information format, etc., no further changes here. Here's no more trouble demo.
Call the contents of the Wp_query height custom call post Type
The above operation relies on templates, and if you need to be highly customizable or call a list in a module of a page, you need to use the Wp_query class to invoke:

$args = Array (' Post_type ' => ' product ', ' posts_per_page ' =>);
$loop = new Wp_query ($args);
while ($loop->have_posts ()): $loop->the_post ();
 The_title ();
 Echo ' <div class= ' entry-content ' > ';
 The_content ();
 Echo ' </div> ';

After the query is the same as the regular main loop, the custom output structure can be.
Display the contents of the custom post Type in the home page list
Although we have customized the post Type at the same time also wrote some content, but in the first page of the list does not appear. The contents of the custom post Type are not automatically mixed into the main loop. So how do you make the contents of a custom post Type appear?
You need to use the pre_get_posts action to do some processing:

Add_action (' pre_get_posts ', ' add_my_post_types_to_query ');
function Add_my_post_types_to_query ($query) {
 if (is_home () && $query->is_main_query ())
  $ Query->set (' Post_type ', Array (' Post ', ' page ', ' movie '));
 return $query;

The Post_type array set in the above $query variable is the content to be displayed in the main loop, and your custom post type can be filled in and displayed on the home page.
to set a fixed connection for a custom post type
to create a new Post type is sometimes also to make it easier to do SEO, so setting its fixed connection is also important. The main use here is the rewrite parameter in the parameter array of the registered post type, which is commonly used in the following two items:
slug = To customize the fixed-connection structure alias, by default, by using the Post type name (for example, the movie of this example), which can be translated. In general, the post type name may be used differently than the URL actually required (the post type is movie, but the URL may require movies). The
With_front = "Fixed connection is based on the root directory." If you set up your structure for/archives/in the Fixed Connection Settings page, then your Post Type generates a connection that defaults to/archives/movie if you set the entry to false you can remove the preceding/archives/and generate the fixed connection directly based on the root path. The
is done, but this is just the most basic usage of post type, post type has other more advanced usage, and more detailed parameter configuration requires you to dig further to fit the functional requirements of your site.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.