Home > Backend Development > PHP Tutorial > Example tutorial for setting Post Type custom article type in WordPress, wordpress example tutorial_PHP tutorial

Example tutorial for setting Post Type custom article type in WordPress, wordpress example tutorial_PHP tutorial

WBOY
Release: 2016-07-12 08:52:46
Original
1287 people have browsed it

An example tutorial on setting Post Type custom post type in WordPress, wordpress example tutorial

What is a custom post?
Don’t take it for granted that the post here refers to the articles in the blog. It is just a proxy for articles. You can even think of it as content.
There is no very standard rule for custom models. The article model can be any content model you want. For example, WordPress itself has the following built-in content article models:

  • Blog Post
  • Page
  • Attachment
  • Correction
  • Navigation etc.

You can understand it this way: it is just a very flexible content form used to create, edit and store data just like we use blog posts.

However, I still need to remind you that the built-in post in the blog is a little different. You can use it to identify content with categories, tags, etc.!
Why customize the article model?
WordPress already provides some well-established default post models that are suitable for most sites, but we still need more options. I’ve listed some content models that come to mind that might be useful and linked to corresponding examples.

  • Property List
  • Event Calendar (I know a lot of people are interested in this)
  • Film and TV Database
  • Book Database
  • Forum system without many integration issues
  • Ticketing system similar to WordPress Trac
  • Design photo album or portfolio

You can also think of more content models than what I listed. And I also want to learn more ideas about forums and ticketing systems in the future. I have implemented these two systems and would love to get some feedback.

Create a post type
To create a new Post Type, you need to use the register_post_type function to register it. This function needs to be called in your theme’s functions.php file:

register_post_type( $post_type, $args );
Copy after login

The $post_type parameter is the name of your customized Post Type. Post Type has many customizable functions, so there will be many $args parameters in this function. So you usually use the following format to register:

function my_custom_post_product() {
  $args = array();
  register_post_type( 'product', $args ); 
}
add_action( 'init', 'my_custom_post_product' );
Copy after login

Wrap it in a function, define an array, and then attach it to the init action. In this way, when WordPress is initialized, it will execute this function to register a custom Post Type, because when register_post_type() is called, it must be before the admin_menu action and after the after_setup_theme action, so it is best to attach it to the init action.
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' );
Copy after login

For the sake of intuition and convenience, I used Chinese directly. It would be better to use English and then translate it into Chinese through the localization function.
There are a lot of parameters. You can also use the generatewp tool to customize the parameters and then change them, which will be a little more convenient.
From the above code, you can see that there is a labels configuration item in the $args array, which is used to configure content related to display copywriting. For clarity, I created an array separately. You can guess the general meaning of other configuration items by reading them in English. If you want to know more about them, you can read the official document: register_post_type.
Add the above code to the bottom of theme functions.php. When you enter the background, you will find an additional Movies option, which means the registration is successful:

2016510155202407.jpg (978×716)

At this time we can create a new Movie and 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, they can be divided into categories such as science fiction, action, war, etc. Then we will add a classification function to the customized Movie, so that we can edit new categories and classify our movies. This classification is the same as the classification in the article.
To add a classification function, you need to use the function register_taxonomy. The method of use is also very simple. It is similar to the registration Post Type function, except that there is one more parameter to specify the corresponding Post Type:

register_taxonomy( $taxonomy, $object_type, $args );
Copy after login

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

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 );
Copy after login

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

2016510155316892.jpg (2558×1406)

这里我们添加两个分类作为演示。
为 Post Type 添加自定义 Meta Box
我们想要添加的电影类型不能仅仅只有正文内容,我们还需要额外添加一些 导演 之类的有关内容。那么就需要添加自定义 Meta Box,Meta Box 可以在文章发表页面中添加自定义的表单,编写文章的时候可以填写额外的信息然后在前端调用出来。
自定义 Meta Box 需要用到 add_meta_box 函数:

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

老规矩,具体参数内容查看官方文档,这里只介绍常用用法。我们注册一个 Meta Box :

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

然后在配置参数里面指定了回调函数 movie_director_meta_box,我们需要在这个函数里面创建表单:

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="<&#63;php echo esc_attr( $value ); &#63;>" placeholder="输入导演名称" >
  <&#63;php
}
Copy after login

这样就可以在文章界面边栏显示出来刚刚创建的表单了:

2016510155409367.png (638×694)

但是这时候,你的表单是没法用的,因为你提交文章之后并没有保存这个 Meta Box 的内容,下面是验证保存内容的代码:

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 );
}
Copy after login

虽然最关键的函数就在最后一句,但是一定要注意安全的校验。把这些代码添加进 functions.php 文件之后,你的 Meta Box 就可以正常工作了。如果你需要更多表单,按照这个模式自定义表单结构,然后添加保存函数即可。
下面,我们迫不及待的添加两部电影《鱼与锅之战:宿命对决》 和 《鱼与锅之战:我爱水煮鱼》 内容如下:

2016510155440232.jpg (2194×1196)

2016510155506733.jpg (2186×1258)

添加完之后,我们可以看下所有电影:

2016510155526928.jpg (2204×714)

列表空荡荡的,好难看,我可不可以加上导演字段?当然可以,使用 [manage $post type posts custom column](http://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column) 即可实现,我们添加:

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;
}
Copy after login

即添加了列导演字段,并从每篇文章中读取出来。这样我们的列表就变成了:

2016510155555944.png (1608×474)

OK,我们的后端部分就这样愉快的完成了。打开生成好的链接看下,咦,Not Found?是这样的,如果你的网站设置了固定连接,当你新建了 Post Type 之后,你必须要在后台更新一下固定连接设置才行。找到后台固定连接,再点击一下下面的“保存设置”,之后就可以正常访问了。
展示 Post Type 的内容
单纯创建 Post Type 只是可以让你输入内容,没有什么意义,我们还需要在前台输出自定义 Post Type 的内容。
自定义 Post Type 的模板和样式
根据 WordPress 的模板调用规则 我们可以得知,我们只需要创建 archive-[post_type].php 和 single-[post_type].php 就可以实现该 Post Type 的列表自定义和文章自定义。当访问 Post Type,WordPress 会优先调用这些模板来渲染。
需要注意的是,你需要在注册 Post Type 的时候设置 'has_archive' => true 才会有列表。
现在我们就把主题里自带的 archive.php 和 single.php 文件复制一份命名为 archive-movie.php 和 single-movie.php,为了演示,这里我不做很多自定义,只是输出导演信息表示一下。
我们分别在 L.56 和 L.23 附近的合适位置输出 Meta Box 信息:

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

然后刷新访问电影列表和具体的电影就可以看到输出的导演信息了。
这里只是举个例子,实际中往往会自定义结构和输出的信息格式等,这里不再进一步修改。这里不再麻烦演示了。
调用 WP_Query 高度自定义调用 Post Type 的内容
上面操作依赖模板,如果需要高度自定义或者在页面的某个模块中调用列表,就需要用到 WP_Query 类来调用:

$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;
Copy after login

查询出来之后就跟常规的主循环一样了,自定输出结构即可。
在首页列表中显示自定义 Post Type 的内容
虽然我们自定义好了 Post Type 同时也编写了一些内容,但是在首页的列表里面并没有显示出来。自定义的 Post Type 的内容不会自动混入主循环里面。那如何让自定义 Post Type 的内容显示出来?
你需要使用 pre_get_posts 这个 action 来做一些处理:

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;
}
Copy after login

在上面的 $query 变量里面设置的 post_type 数组就是要在主循环里面展示的内容,将你的自定义 Post Type 填写进去就可以在首页中显示出来了。
设置自定义 Post Type 的固定连接
创建一个新的 Post Type 有时候也是为了更方便做 SEO,所以设置它的固定连接也非常重要。这里主要用到注册 Post Type 的参数数组里面的 rewrite 参数,常用以下几两项:
slug =》自定义固定连接结构别名,默认是使用 Post Type 名(例如本例的 movie),可以被翻译。一般来说 Post Type 名可能与实际需要的 URL 不一样( Post Type 为 movie,但 URL 可能需要 movies),就可使用该项自定义。
with_front =》 固定连接是否以根目录为基础路径。如果你在固定连接设置页面设置你的结构为 /archives/,那么你的 Post Type 生成的连接默认为 /archives/movie 如果设置该项为 false 即可去掉前面的 /archives/ 直接基于根路径生成固定连接。
大功告成,但这只是 Post Type 最基础的用法,Post Type 还有其他更高级的用法,更详细的参数配置还需要你去进一步挖掘来适应你网站的功能需求。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1125886.htmlTechArticleWordPress中设置Post Type自定义文章类型的实例教程,wordpress实例教程 什么是自定义post 不要想当然的认为这里的post就是就是指博客中的文章,...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template