WordPress set Post Type custom article types example tutorial, wordpress instance Tutorial _php Tutorial

Source: Internet
Author: User

WordPress set Post Type custom article types example tutorial, wordpress instance Tutorial

What is a custom post?
Don't take it for granted that the post here is just a blog post, it's just a surrogate word for an article class, and you can even think of it as content.
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 into the following several content article model:

    • Blog posts
    • Page
    • Attachment
    • Correction
    • Navigation, etc.

You can understand it as long as it's a very flexible form of content that we use to create, edit, and store data using blog posts.

But here I still need to remind, blog built-in post or a little bit different, you can use it contains categories, tags, etc. to identify content!
Why do you want to customize the article model?
WordPress has provided some perfect default article models and is suitable for most sites, but we still need more choices. I have listed some of the possible useful content models that I think of and link to the corresponding examples.

    • Property List
    • Event Calendar (I know a lot of people are interested in this)
    • Film and television data base
    • Books database
    • A forum system that does not have many integration issues
    • A ticketing system similar to WordPress TRAC
    • Design albums or folios

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

Create a Post Type
Creating a new Post Type requires using the Register_post_type function to register. This function needs to be lowered in your subject's functions.php file:

Register_post_type ($post _type, $args);

$post the _type parameter is the name of your custom post type, the post type can be customized to a very large number of functions, so there are many $args parameters in this function. Therefore, the following format is usually used to register:

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 anchored to the action of Init. So WordPress at initialization time, will execute this function to register a custom post Type, because call Register_post_type (), must be before Admin_menu action, in After_setup_ Theme action, so it's best to be anchored to the init action.
Many parameters, in order to write tutorials convenient, only list the more commonly used parameters, the general structure is as follows:

function My_custom_post_movie () {$labels = array (' name ' = = _x (' Movies ', ' Post type 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 movie '), ' All_     Items ' = + __ (' All movies '), ' View_item ' + __ (' view movie '), ' search_items ' + __ (' Search movie '), ' Not_found '     + __ (' No movies Found '), ' Not_found_in_trash ' + __ (' No related movies in Recycle Bin '), ' parent_item_colon ' = ', ' Menu_name ' = ' Movies '); $args = Array (' labels ' + $labels, ' description ' = ' The movie information of our website ', ' public ' = ' true ', ' menu_position ' =& Gt 5, ' supports ' = = Array (' title ', ' editor ', ' thumbnail ', ' excerpt ', ' comments '), ' has_archive ' = true); Register_post_type (' movie ', $args);} Add_action (' init ', ' My_custom_post_movie '); 

Here for the sake of intuitive convenience, I directly use the Chinese language, it should be better to use English and then through the localization function to translate into Chinese.
There are a number of parameters, you can also use the GENERATEWP tool to customize the parameters, and then change, it will be a little easier.
You can see from the above code 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 you can guess the general meaning in English, if you want to know more, you can look at the official document: Register_post_type.
Add the above code to the bottom of the topic functions.php, you will 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 film type of article. But this is basically the same as the article type, and we need more customization to refine our Movie genre.
Adding a classification function for Post Type
As far as movies are concerned, they can be classified as sci-fi, action, war, and so on, so we'll add a sort function to the custom movie so we can edit the new categories and categorize our movies. This classification is the same as the nature of the classification in the article.
Adding the classification function requires the use of the function register_taxonomy, which is also very simple, similar to registering the Post type function, except that a 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 category ', ' Taxonomy name '),  ' Singular_name ' C3/>=> _x (' movie category ', ' taxonomy singular name '),  ' search_items ' +   __ (' Search movie category '),  ' all_items ' +     __ (' All movie categories '),  ' Parent_item ' +    __ (' Superior classification of the movie category '),  ' Parent_item_colon ' + __ (' The superior category of the movie Category: '),  ' Edit_item ' +     __ (' Edit movie category '),  ' Update_item ' +    __ (' Update movie category '),  ' Add_new_item ' +   __ (' Add a new movie category '),  ' new_item_name ' +   __ (' new movie category '),  ' Menu_name '     (' movie category '), "$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 saw the familiar article classification function, but the above copy all became our custom content:

Here we add two categories as a demo.
Add a custom Meta Box for Post Type
The type of movie we want to add is not just the body content, we also need to add some additional content such as directors. Then you need to add a custom Meta box,meta box to add a custom form to the post page, write the article with additional information and then call it out at the front.
The custom Meta Box needs to use the Add_meta_box function:

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

The usual, specific parameters to view official documents, this is only common usage. We register 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 we specify the callback function Movie_director_meta_box in the configuration parameter, we need to create the form inside this function:

function Movie_director_meta_box ($post) {  //create temporary hidden form for secure  wp_nonce_field (' Movie_director_meta_box ', ' Movie_director_meta_box_nonce ');  Gets the value previously stored  $value = Get_post_meta ($post->id, ' _movie_director ', true);  ? >      <?php}

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

However, your form is not available at this time because you did not save the contents of the Meta Box after you submitted the article, the following is the code that validates the saved content:

Add_action (' Save_post ', ' movie_director_save_meta_box '); function Movie_director_save_meta_box ($post _id) {  // Security checks  //check whether to send a one-time hidden form content (to determine if a third party simulation submitted)  if (! isset ($_post[' movie_director_meta_box_nonce '))) {    return;  }  Determine if the value of the hidden form is the same as before  if (! wp_verify_nonce ($_post[' movie_director_meta_box_nonce '), ' Movie_director_meta_box ') {    return;  }  Determine if the user has permissions  if (! Current_user_can (' Edit_post ', $post _id)) {    return;  }  Determine if the Meta Box is 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 security check. After adding the code into the functions.php file, your Meta Box will work. If you need more forms, customize the form structure in this mode, and then add the Save function.
Below, we can't wait to add two movies "Fish and pot Battle: Fate Duel" and "Fish and pot battle: I love boiled fish" content as follows:

Once added, we can see all the movies:

List empty, so ugly, can I add the Director field? Yes, you can, using [manage $post type posts custom column] (http://codex.wordpress.org/plugin_api/action_reference/manage_$post_ Type_posts_custom_column) can be implemented, 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    "Movie_director":      Echo Get_post_meta ($post->id, ' _movie_director ', true);      break;  }} function Movie_edit_columns ($columns) {  $columns [' movie_director '] = ' director ';  return $columns;}

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

OK, our back end part is so happy to finish. Open the generated 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, then click on the "Save Settings" below, then you can access the normal.
Show the contents of Post Type
Simply creating post type just lets you enter content, no meaning, and we also need to output the content of the custom Post type in the foreground.
Templates and styles for customizing post Type
Based on the WordPress template invocation rules we can tell that we only need to create archive-[post_type].php and single-[post_type].php to implement the Post type list customization and article customization. When accessing Post type,wordpress, these templates are invoked first to render.
It is important to note that you will need to set ' has_archive ' to true to have a list when registering the Post Type.
Now we will be the theme of the archive.php and single.php files are copied a copy named archive-movie.php and single-movie.php, in order to demonstrate, here I do not do a lot of customization, just output director information to express.
We output Meta Box information in a suitable location near l.56 and L.23, respectively:

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

Then refresh to access the movie list and the specific movie to see the output of the director message.
Here are just a few examples of the fact that the structure and output of the information format are often customized, and no further modification is given here. There's no more trouble with the demo.
Call Wp_query height to customize the content of the call Post Type
The above action relies on the template, and if you need a high degree of customization 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->ha Ve_posts ()): $loop->the_post (); The_title (); Echo '; The_content (); Echo '; endwhile;

After the query is the same as the regular main loop, self-defined output structure can be.
Display the contents of a custom Post Type in the home page list
Although we have customized the post Type to write some content, it is not shown in the list on the home page. The contents of the custom post Type are not automatically mixed into the main loop. How do I get the contents of the custom post Type to 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 $qu ery;}

The Post_type array set in the above $query variable is what you want to show in the main loop, and your custom post type can be displayed in the home page.
To set a fixed connection for a custom Post Type
Creating a new Post Type is also sometimes necessary to make SEO easier, so it is important to set up a fixed connection. This is mainly used to register the Post Type parameter array inside the rewrite parameter, often the following two items:
slug = "Custom fixed connection structure alias, the default is to use the Post Type name (such as this example of movie), can be translated. In general, the post type name may not be the same as the URL that is actually needed (post type is movie, but the URL may need to be movies), which you can use to customize it.
With_front = Fixed whether the connection is based on the root directory path. If you set your structure to/archives/in the Fixed Connection Settings page, then your Post Type generated connection defaults to/archives/movie if you set this entry to false you can remove the previous/archives/to generate a fixed connection directly based on the root path.
Done, but this is only the post type most basic usage, post type and other more advanced usage, more detailed parameter configuration also need you to dig further to adapt to your site's functional requirements.

http://www.bkjia.com/PHPjc/1125886.html www.bkjia.com true http://www.bkjia.com/PHPjc/1125886.html techarticle WordPress set Post Type custom article types of instances tutorial, wordpress instance Tutorial What is Custom post do not take for granted that the post in this place is referring to the blog article, ...

  • Related Article

    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: info-contact@alibabacloud.com 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.