Skip to main content
We are Brand SEO Beijing serving international business, your marketing partner, Contact us by mi@mgsh.com.cn

Website CMS Custom Post Type - Single Post Type

What is Post Type?

There are two commonly used Post Types built into WordPress: Post (article) and Page (page), which are used to display two types of content, one is a relatively dynamic article, and the other is a relatively fixed page.
In addition, WordPress also has several other Post Types built in to display different types of content.But if it is a more complex website or requires a high degree of customization, you can manually create a Post Type to display certain types of information.
For example, for a large magazine website, you can create a different Post Type for the magazine type to manage; for a large enterprise website, you can create a different Post Type for the product type to display.
This tutorial takes creating a Movies Post Type as an example to introduce a series of things related to Post Type.After creation, we can create a new movie introduction, each movie can add its own information such as director, and can also create a separate movie list.
The theme used is official twentyfourteen, it is recommended to modify the test on the local server while watching.

Create a post type

Creating a new Post Type requires registering it with a function.need in your theme functions.php The function is called from the file:

register_post_type( $post_type, $args );

$post_type The parameter is the name of your custom Post Type. Post Type can have many custom functions, so the function in this function $args There will be many parameters.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 it in a function, define an array, and then attach to init on this action.In this way, when WordPress is initialized, it will execute this function to register a custom Post Type, because the call register_post_type() , it must be admin_menu before action, in after_setup_theme After action, so it's best to link to init action on.
There are many parameters. For the convenience of writing tutorials, only the more commonly used parameters are listed. The general structure is as follows:

function my_custom_post_movie() {
  $labels = array(
    'name'               => _x( 'Movies', 'post type 名称' ),
    'singular_name'      => _x( 'Movie', 'post type 单个 item 时的名称,因为英文有复数' ),
    'add_new'            => _x( '新建电影', '添加新内容的链接名称' ),
    'add_new_item'       => __( '新建一个电影' ),
    'edit_item'          => __( '编辑电影' ),
    'new_item'           => __( '新电影' ),
    'all_items'          => __( '所有电影' ),
    'view_item'          => __( '查看电影' ),
    'search_items'       => __( '搜索电影' ),
    'not_found'          => __( '没有找到有关电影' ),
    'not_found_in_trash' => __( '回收站里面没有相关电影' ),
    'parent_item_colon'  => '',
    'menu_name'          => 'Movies'
  );
  $args = array(
    'labels'        => $labels,
    'description'   => '我们网站的电影信息',
    'public'        => true,
    'menu_position' => 5,
    'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
    'has_archive'   => true
  );
  register_post_type( 'movie', $args );
}
add_action( 'init', 'my_custom_post_movie' );

For the sake of intuition and convenience, I use Chinese directly. It is better to use English and then translate it into Chinese through localization functions.
There are a lot of parameters, you can also use the tool to customize the parameters, and then change them, it will be a little more convenient.
As you can see from the above code $args There is one in the array labels The configuration item is used to configure the content related to the display text. For clarity, it is taken out separately to create an array.You can also guess the general meaning of other configuration items in English. If you want to know more about it, you can read the official documentation: .
Add the above code to the theme functions.php At the bottom, enter the background and you will find more Movies option, this means that the registration is successful:
custom type
At this time, we can create a new Movie to publish a movie-type article.But this is basically the same as the article type, we need more customization to complete our Movie type.

Add classification function to Post Type

As far as movies are concerned, it can be divided into categories such as sci-fi, action, war, etc., then we add a classification function to the custom Movie, so that we can edit the new classification and classify our movies.This category is the same as the category in the article.
Adding the classification function requires the use of functions, and the method of use is very simple, similar to the registered Post Type function, except that there is one more parameter to specify the corresponding Post Type:

register_taxonomy( $taxonomy, $object_type, $args );

For this example, the following common parameters can be configured:

function my_taxonomies_movie() {
  $labels = array(
    'name'              => _x( '电影分类', 'taxonomy 名称' ),
    'singular_name'     => _x( '电影分类', 'taxonomy 单数名称' ),
    'search_items'      => __( '搜索电影分类' ),
    'all_items'         => __( '所有电影分类' ),
    'parent_item'       => __( '该电影分类的上级分类' ),
    'parent_item_colon' => __( '该电影分类的上级分类:' ),
    'edit_item'         => __( '编辑电影分类' ),
    'update_item'       => __( '更新电影分类' ),
    'add_new_item'      => __( '添加新的电影分类' ),
    'new_item_name'     => __( '新电影分类' ),
    'menu_name'         => __( '电影分类' ),
  );
  $args = array(
    'labels' => $labels,
    'hierarchical' => true,
  );
  register_taxonomy( 'movie_category', 'movie', $args );
}
add_action( 'init', 'my_taxonomies_movie', 0 );

After adding it to the theme, we see the familiar article classification function, but the above copy has all become our custom content:
custom taxonomy
Here we add two categories for demonstration.

Add custom Meta Box for Post Type

The type of movie we want to add can not only be the body content, we also need to add some additional content such as the director.Then you need to add a custom Meta Box. Meta Box can add a custom form to the article publishing page. When writing an article, you can fill in additional information and call it on the front end.
Custom Meta Box needs to use functions:

add_meta_box( $id, $title, $callback, $post_type, $context,$priority, $callback_args );

Old rules, please refer to the official documentation for specific parameters. Only common usage is introduced here.We register a Meta Box:

add_action( 'add_meta_boxes', 'movie_director' );
function movie_director() {
    add_meta_box(
        'movie_director',
        '电影导演',
        'movie_director_meta_box',
        'movie',
        'side',
        'low'
    );
}

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

function movie_director_meta_box($post) {
    // 创建临时隐藏表单,为了安全
    wp_nonce_field( 'movie_director_meta_box', 'movie_director_meta_box_nonce' );
    // 获取之前存储的值
    $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="输入导演名称" >
    <?php
}
[/code]
这样就可以在文章界面边栏显示出来刚刚创建的表单了:
<img src="https://cdn.wpjam.com/qiniu/4713/image/392b06bf8a73eb190011ec9d85e5588d.png?imageView2/2/w/1200/interlace/1/q/70|watermark/1/image/aHR0cHM6Ly9jZG4ud3BqYW0uY29tL3dwamFtL3dhdGVybWFyay5wbmc=/dissolve/100/gravity/SouthEast/dx/10/dy/10#" alt="自定义 Meta Box" />
但是这时候,你的表单是没法用的,因为你提交文章之后并没有保存这个 Meta Box 的内容,下面是验证保存内容的代码:
[code]
add_action( 'save_post', 'movie_director_save_meta_box' );
function movie_director_save_meta_box($post_id){
    // 安全检查
    // 检查是否发送了一次性隐藏表单内容(判断是否为第三者模拟提交)
    if ( ! isset( $_POST['movie_director_meta_box_nonce'] ) ) {
        return;
    }
    // 判断隐藏表单的值与之前是否相同
    if ( ! wp_verify_nonce( $_POST['movie_director_meta_box_nonce'], 'movie_director_meta_box' ) ) {
        return;
    }
    // 判断该用户是否有权限
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
    // 判断 Meta Box 是否为空
    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, we must pay attention to security verification.add these codes to functions.php After the file, your Meta Box should work fine.If you need more forms, customize the form structure according to this pattern, and then add the save function.
Below, we can't wait to add two films, "Fish vs. Pot: Destiny Showdown" and "Fish vs. Pot: I Love Boiled Fish". The content is as follows:
movie 1
movie 2
After adding, we can watch all the movies:
Custom Movie List
The list is empty and ugly, can I add the director field?Of course you can, use To do this, 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'] = '导演';
    return $columns;
}

That is, the column director field is added and read from each article.So our list becomes:
Custom Movie List
OK, our backend part is finished happily.Open the generated link and take a look. Hey, Not Found?That's right, if your website is set up with a fixed connection, when you create a new Post Type, you must update the fixed connection settings in the background.Find the background fixed connection, and then click "Save Settings" below, and then you can access it normally.

Display the content of Post Type

Simply creating a Post Type just allows you to enter the content, which is meaningless. We also need to output the content of the custom Post Type in the foreground.

Customize Post Type templates and styles

From what we can tell, we just need to create archive-[post_type].php 和 single-[post_type].php The list customization and article customization of the Post Type can be realized.When accessing Post Type, WordPress will first call these templates to render.
It should be noted that you need to set the Post Type when registering 'has_archive' => true There will be a list.
Now let's put the one that comes with the theme archive.php 和 single.php A copy of the file named archive-movie.php 和 single-movie.php, for demonstration, I don't do a lot of customization here, just output the director information to show it.
We output the Meta Box information at appropriate positions near L.56 and L.23, respectively:

echo '导演:'.get_post_meta( get_the_ID(), '_movie_director', true );

Then refresh the access movie list and the specific movie to see the output director information.
This is just an example. In practice, the structure and output information format are often customized, and no further modifications are made here.No more hassle with demos here.

Call WP_Query to highly customize what to call Post Type

The above operation depends on the template. If you need to highly customize or call the list in a module of the page, you need to use the WP_Query class to call:

$args = array( 'post_type' => 'product', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
  the_title();
  echo '
<div class="entry-content">';
  the_content();
  echo '</div>
';
endwhile;

After the query comes out, it is the same as the regular main loop, and you can customize the output structure.

Display the content of the custom Post Type in the homepage list

Although we customized the Post Type and wrote some content, it was not displayed in the list on the home page.The content of the custom Post Type will not be automatically mixed into the main loop.How to make the content of the custom Post Type displayed?
You need to use this 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;
}

above $query set in the variable post_type The array is the content to be displayed in the main loop. Fill in your custom Post Type and it will be displayed on the home page.

Set up a fixed connection for a custom Post Type

Creating a new Post Type is sometimes for the convenience of SEO, so setting its fixed connection is also very important.This is mainly used in the parameter array of the registered Post Type. rewrite Parameters, the following two are commonly used:

  • slug => Customize the fixed connection structure alias, the default is to use the Post Type name (such as the movie in this example), which can be translated.Generally speaking, the Post Type name may not be the same as the actual URL required (the Post Type is movie, but the URL may need movies), you can use this customization.
  • with_front => Whether the fixed connection is root-based path.If you set your structure on the fixed connection settings page as /archives/, then the connection generated by your Post Type defaults to /archives/movie If you set this to false remove the previous /archives/ Generate fixed connections directly based on the root path.

You're done, but this is only the most basic usage of Post Type, there are other more advanced usages of Post Type, and more detailed parameter configuration requires you to dig further to adapt to the functional requirements of your website.

Reprinted from: https://www.it131.org/10856.html
Author: blog.wpjam.com
Back to Top