


Example tutorial for setting Post Type custom article type in WordPress, wordpress example tutorial_PHP tutorial
Jul 12, 2016 am 08:52 AMAn 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 );
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' );
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 時的名稱,因為英文有復數(shù)' ), 'add_new' => _x( '新建電影', '添加新內(nèi)容的鏈接名稱' ), 'add_new_item' => __( '新建一個電影' ), 'edit_item' => __( '編輯電影' ), 'new_item' => __( '新電影' ), 'all_items' => __( '所有電影' ), 'view_item' => __( '查看電影' ), 'search_items' => __( '搜索電影' ), 'not_found' => __( '沒有找到有關(guān)電影' ), 'not_found_in_trash' => __( '回收站里面沒有相關(guān)電影' ), 'parent_item_colon' => '', 'menu_name' => 'Movies' ); $args = array( 'labels' => $labels, 'description' => '我們網(wǎng)站的電影信息', '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 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:
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 );
For this example, you can configure the following common parameters:
function my_taxonomies_movie() { $labels = array( 'name' => _x( '電影分類', 'taxonomy 名稱' ), 'singular_name' => _x( '電影分類', 'taxonomy 單數(shù)名稱' ), '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 topic, we see the familiar article classification function, but all the copy above has become our customized content:
這里我們添加兩個分類作為演示。
為 Post Type 添加自定義 Meta Box
我們想要添加的電影類型不能僅僅只有正文內(nèi)容,我們還需要額外添加一些 導演 之類的有關(guān)內(nèi)容。那么就需要添加自定義 Meta Box,Meta Box 可以在文章發(fā)表頁面中添加自定義的表單,編寫文章的時候可以填寫額外的信息然后在前端調(diào)用出來。
自定義 Meta Box 需要用到 add_meta_box 函數(shù):
add_meta_box( $id, $title, $callback, $post_type, $context,$priority, $callback_args );
老規(guī)矩,具體參數(shù)內(nèi)容查看官方文檔,這里只介紹常用用法。我們注冊一個 Meta Box :
add_action( 'add_meta_boxes', 'movie_director' ); function movie_director() { add_meta_box( 'movie_director', '電影導演', 'movie_director_meta_box', 'movie', 'side', 'low' ); }
然后在配置參數(shù)里面指定了回調(diào)函數(shù) movie_director_meta_box,我們需要在這個函數(shù)里面創(chuàng)建表單:
function movie_director_meta_box($post) { // 創(chuàng)建臨時隱藏表單,為了安全 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 }
這樣就可以在文章界面邊欄顯示出來剛剛創(chuàng)建的表單了:
但是這時候,你的表單是沒法用的,因為你提交文章之后并沒有保存這個 Meta Box 的內(nèi)容,下面是驗證保存內(nèi)容的代碼:
add_action( 'save_post', 'movie_director_save_meta_box' ); function movie_director_save_meta_box($post_id){ // 安全檢查 // 檢查是否發(fā)送了一次性隱藏表單內(nèi)容(判斷是否為第三者模擬提交) if ( ! isset( $_POST['movie_director_meta_box_nonce'] ) ) { return; } // 判斷隱藏表單的值與之前是否相同 if ( ! wp_verify_nonce( $_POST['movie_director_meta_box_nonce'], 'movie_director_meta_box' ) ) { return; } // 判斷該用戶是否有權(quán)限 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 ); }
雖然最關(guān)鍵的函數(shù)就在最后一句,但是一定要注意安全的校驗。把這些代碼添加進 functions.php 文件之后,你的 Meta Box 就可以正常工作了。如果你需要更多表單,按照這個模式自定義表單結(jié)構(gòu),然后添加保存函數(shù)即可。
下面,我們迫不及待的添加兩部電影《魚與鍋之戰(zhàn):宿命對決》 和 《魚與鍋之戰(zhàn):我愛水煮魚》 內(nèi)容如下:
添加完之后,我們可以看下所有電影:
列表空蕩蕩的,好難看,我可不可以加上導演字段?當然可以,使用 [manage $post type posts custom column](http://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column) 即可實現(xiàn),我們添加:
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; }
即添加了列導演字段,并從每篇文章中讀取出來。這樣我們的列表就變成了:
OK,我們的后端部分就這樣愉快的完成了。打開生成好的鏈接看下,咦,Not Found?是這樣的,如果你的網(wǎng)站設置了固定連接,當你新建了 Post Type 之后,你必須要在后臺更新一下固定連接設置才行。找到后臺固定連接,再點擊一下下面的“保存設置”,之后就可以正常訪問了。
展示 Post Type 的內(nèi)容
單純創(chuàng)建 Post Type 只是可以讓你輸入內(nèi)容,沒有什么意義,我們還需要在前臺輸出自定義 Post Type 的內(nèi)容。
自定義 Post Type 的模板和樣式
根據(jù) WordPress 的模板調(diào)用規(guī)則 我們可以得知,我們只需要創(chuàng)建 archive-[post_type].php 和 single-[post_type].php 就可以實現(xiàn)該 Post Type 的列表自定義和文章自定義。當訪問 Post Type,WordPress 會優(yōu)先調(diào)用這些模板來渲染。
需要注意的是,你需要在注冊 Post Type 的時候設置 'has_archive' => true 才會有列表。
現(xiàn)在我們就把主題里自帶的 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 );
然后刷新訪問電影列表和具體的電影就可以看到輸出的導演信息了。
這里只是舉個例子,實際中往往會自定義結(jié)構(gòu)和輸出的信息格式等,這里不再進一步修改。這里不再麻煩演示了。
調(diào)用 WP_Query 高度自定義調(diào)用 Post Type 的內(nèi)容
上面操作依賴模板,如果需要高度自定義或者在頁面的某個模塊中調(diào)用列表,就需要用到 WP_Query 類來調(diào)用:
$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;
查詢出來之后就跟常規(guī)的主循環(huán)一樣了,自定輸出結(jié)構(gòu)即可。
在首頁列表中顯示自定義 Post Type 的內(nèi)容
雖然我們自定義好了 Post Type 同時也編寫了一些內(nèi)容,但是在首頁的列表里面并沒有顯示出來。自定義的 Post Type 的內(nèi)容不會自動混入主循環(huán)里面。那如何讓自定義 Post Type 的內(nèi)容顯示出來?
你需要使用 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; }
在上面的 $query 變量里面設置的 post_type 數(shù)組就是要在主循環(huán)里面展示的內(nèi)容,將你的自定義 Post Type 填寫進去就可以在首頁中顯示出來了。
設置自定義 Post Type 的固定連接
創(chuàng)建一個新的 Post Type 有時候也是為了更方便做 SEO,所以設置它的固定連接也非常重要。這里主要用到注冊 Post Type 的參數(shù)數(shù)組里面的 rewrite 參數(shù),常用以下幾兩項:
slug =》自定義固定連接結(jié)構(gòu)別名,默認是使用 Post Type 名(例如本例的 movie),可以被翻譯。一般來說 Post Type 名可能與實際需要的 URL 不一樣( Post Type 為 movie,但 URL 可能需要 movies),就可使用該項自定義。
with_front =》 固定連接是否以根目錄為基礎(chǔ)路徑。如果你在固定連接設置頁面設置你的結(jié)構(gòu)為 /archives/,那么你的 Post Type 生成的連接默認為 /archives/movie 如果設置該項為 false 即可去掉前面的 /archives/ 直接基于根路徑生成固定連接。
大功告成,但這只是 Post Type 最基礎(chǔ)的用法,Post Type 還有其他更高級的用法,更詳細的參數(shù)配置還需要你去進一步挖掘來適應你網(wǎng)站的功能需求。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

To create an account on WordPress, simply visit its website, select the registration option, fill in the registration form, and verify your email address. Other ways to register include using a Google account or Apple ID. The benefits of signing up include creating a website, gaining features, joining the community, and gaining support.
