Panduan tipe post khusus wordpress: pembuatan, tampilan dan meta box

  -  

Do you want to create a WordPress custom post type? It’s an excellent và useful way to lớn organize your website if you’re running several types of nội dung all at once.

Bạn đang xem: Panduan tipe post khusus wordpress: pembuatan, tampilan dan meta box

In this tutorial, you will learn how to make a WordPress custom post type by building a site-specific plugin.

What Is a WordPress Custom Post Type?

WordPress provides a few mặc định post types, such as Post, Page, Revision, and Attachment. On a small scale, they will represent your blog topic just fine. However, they might not be sufficient after your nội dung becomes more diverse.

That’s where the WordPress custom post type comes inkhổng lồ play. In short, it is an additional post type that you create based on your needs. With it, you’ll be able khổng lồ group your posts more specifically.

Creating a custom post type in WordPress is more efficient than assigning categories to your posts. That’s because categorizing articles places them on the same list, commonly in the Post section. The problem is, if you have sầu more than one broad topic, it will be difficult for you khổng lồ keep trachồng of them.

On the other hvà, it lets you choose a more suitable section for your post right from the start. This should help you classify your content better and more seamlessly.

WordPress custom post type has its own menu in the WordPress admin area, which leads to a list of posts of that particular type.

In the example above sầu, if a user goes khổng lồ the Custom Articles database section of your site, the posts from Post, or Page will not be included. That’s because they belong to lớn their own types.

Not only that, you can help readers narrow down their searches further by grouping posts on your Custom Articles into lớn different categories, lượt thích reviews, Tutorial, etc. Such a great convenience for your visitors, right?

What Can You Change in WordPress Custom Post Type?

When creating a new post type, you have several customization options. You can choose where the menu appears in the admin area, whether that type of post is included in tìm kiếm results, whether it supports excerpts, whether comments are allowed, và so on.

What’s great is that you can also change various pieces of text, such as renaming Add New Post as Add New Custom Article, replace the Featured Image text with Add Poster, & the các mục goes on.

Moreover, WordPress custom post type allows you to enable the custom field feature in the post editor. Thanks khổng lồ this, it’s possible khổng lồ provide more details about your content.

Take a look at our Custom Articles post type example. Besides having the article as its main content, you have sầu the option to lớn add custom fields for information like Author, Reading Time, and so on.

*

However, any custom fields you create are available on all post types. Therefore, a plugin is required lớn limit a specific field khổng lồ only appear for a certain post type. We will explain how lớn do this later on, so keep on reading.

Elements of a WordPress Custom Post Type

To begin, let’s learn how khổng lồ write a new function that calls the register_post_type() function. It should come with two parameters:

The name of the post type that should be no more than trăng tròn characters & must not contain spaces or capital letters. Our custom post type name is article.An associative array named $args that contains information about the post type in ‘key’ => ‘value’ pairs.

IMPORTANT: Remember that the functions must be hooked to lớn the init action hook. Otherwise, your WordPress custom post type will not register correctly.


Lastly, all custom functions should be prefixed to avoid conflicts with other plugins or theme functions. To make them unique, we’ll be using backlinks.vn Tutorials initials for this example – ht.

The initial code khổng lồ add a new custom post type should look lượt thích this:

// The custom function MUST be hooked to the init action hookadd_action( "init", "ht_custom_post_custom_article" );// A custom function that calls register_post_typefunction ht_custom_post_custom_article() // Set various pieces of text, $labels is used inside the $args array $labels = array( "name" => _x( "Custom Articles", "post type general name" ), "singular_name" => _x( "Custom Article", "post type singular name" ), ... ); // Set various pieces of information about the post type $args = array( "labels" => $labels, "description" => "My custom post type", "public" => true, ... ); // Register the post type with all the information contained in the $arguments array register_post_type( "article", $args );Since the $args and $labels are both arrays, it’s better to write the $labels variable first và then the $args variable. Once that is done, you can register the code.

Now, we are going to lớn discuss $args and $labels arrays that we will use to lớn customize the WordPress custom post type.

What Is $args Array?

$args is short for argument and this variable is used to contain arrays. Array, on the other hvà, is a data structure that stores elements (key và value pairs) of an object (WordPress custom post type).

There are many arrays in $args, but we’re going to danh mục only the most commonly used. Keep in mind, however, that they are all optional.

labels – an array that defines various pieces of text, such as the thực đơn name & the name of the WordPress custom post type itself. We’ll talk more about this array later in the $label array section.description – a short & descriptive summary of the post type. This can be shown in the post type’s template và will not be used anywhere else.public – khổng lồ change the visibility of the WordPress custom post type khổng lồ authors and visitors. We’re going khổng lồ phối the value to lớn TRUE lớn make it appear in the WordPress Dashboard.supports – selectively enable various post features such as featured images, excerpts, custom fields, etc. If set khổng lồ FALSE instead of containing an array, it disables the editor for this post type. This will be useful if you want to lớn lock all posts of this type while keeping them visible.has_archive – this key defines three things if mix lớn TRUE – your post type has an archive page, the URL follows your permaliên kết structure, và the slug is the name you entered in parameter 1 of register_post_types(). For instance, http://www.mywebsite.com/article/ shows all Custom Articles posts.show_in_admin_bar – using the TRUE value will make this post type appear in the upper Admin bar, under the +New section.show_in_nav_menus – changes whether posts of this type can be added to lớn navigation menus created via the Appearance -> Menus screen. Here, we’ll need to lớn enter a TRUE value.query_varTRUE or FALSE sets whether or not readers can view a post by entering the post type và post title as a query in the URL, like ‘http://www.mytrang web.com/?article=example-article‘.

What Is $labels Array?

The first array in the $args variable is $labels. What’s quality, is that it’s made khổng lồ contain other arrays. Therefore, it is crucial to create a variable named $labels to lớn hold all the key and value pairs in a separate section. This reduces the risk of writing incorrect code and lớn make the function somewhat more cleaner.

Below are some of the most important keys for the $labels array:

name – the general plural name for the post typesingular_name – the name for a single post of this typeadd_new – replaces the ‘Add New’ textadd_new_item – changes the ‘Add New Post’ textedit_item – adjusts the ‘Edit Post’featured_image – modifies ‘Featured Image’ in the post editorset_featured_image – replaces ‘Set Featured Image’menu_name – alters the text of the top-cấp độ link (the default text for the link is the name key)

You can take a look at the full list of $args and $labels arguments on the WordPress Codex page for register_post_type().

What Is ‘supports’ Array?

One of the keys in the $args array is supports. This is a simple array where you write the các mục of post editor features you want to lớn enable for your WordPress custom post type. By mặc định, only title & editor are enabled.

Xem thêm: Cách Xóa Acc Facebook Vĩnh Viễn Trên Điện Thoại, Máy Tính, Xóa Tài Khoản Facebook Vĩnh Viễn Bằng Cách Nào

However, you can also write FALSE instead of an array. By doing this, you will disable all post-editing features including the title and nội dung area. That way posts can’t be edited but they are still fully visible.

Here is the danh sách of post editor features you can enable in the supports array:

titleeditorauthorthumbnailexcerpttrackbackscustom-fieldscommentsrevisionspage-attributespost-formats

Creating a New Post Type via a Site-Specific Plugin

To create a WordPress custom type, you can either build a site-specific plugin, download a normal plugin, or edit your functions.php file.

The third method is not recommended because your custom post type data might be overwritten after theme update. The second method is also not reliable since your data will disappear once you deactivate the tool.

Therefore, we are going lớn proceed with the first option – building a site-specific plugin. Basically, it’s a custom tool that you can build by yourself for specific tasks.

What’s great about it is that you can keep the data even if you decide khổng lồ update your theme or deactivate the plugin. It’s also highly customizable.

However, this method can get a bit technical. That’s why, khổng lồ help you get started, we encourage you to read our tutorial on how lớn create a WordPress plugin, as well.

Now that we know what elements are required for the function, we can build our plugin, write the custom functions, và hook them to lớn the init action hook.

This is how a finished WordPress custom post type should look like:

__( "Custom Articles" ),"singular_name" => __( "Custom Article" ),"add_new" => __( "Add New Custom Article" ),"add_new_item" => __( "Add New Custom Article" ),"edit_item" => __( "Edit Custom Article" ),"new_item" => __( "New Custom Article" ),"all_items" => __( "All Custom Articles" ),"view_item" => __( "View Custom Article" ),"search_items" => __( "Search Custom Article" ),"featured_image" => "Poster","set_featured_image" => "Add Poster");// The arguments for our post type, to be entered as parameter 2 of register_post_type()$args = array("labels" => $labels,"description" => "Holds our custom article post specific data","public" => true,"menu_position" => 5,"supports" => array( "title", "editor", "thumbnail", "excerpt", "comments", "custom-fields" ),"has_archive" => true,"show_in_admin_bar" => true,"show_in_nav_menus" => true,"query_var" => true,);// Điện thoại tư vấn the actual WordPress function// Parameter 1 is a name for the post type// Parameter 2 is the $args arrayregister_post_type( "article", $args);}Now, to turn this code inlớn a plugin, follow the steps below:

First, open a text editor on your computer. Copy và paste the code.Save it as a PHP file. For this example, we will name it my-custom-post-type.php.

Congratulations, you have sầu just installed a site-specific plugin lớn create a WordPress custom post type!

Customizing New Post Type

To begin customizing your new post types, you just have sầu to upload two corresponding template files to your theme’s main directory. Names of these template files should look like this:

Template for an individual post – single-post-type.phpTemplate for an archive page – archive-post-type.php

The post-type part of the tệp tin names must be the name from parameter 1 of register_post_type(). In this example, the file names should be single-article.php and archive-article.php

If you don’t create templates, WordPress will use single.php and archive sầu.php instead, which keeps all your posts and archives identical.

That being said, the best way to lớn start is lớn duplicate single.php or archive.php and rename them as above sầu. That way the overall structure is identical to lớn the rest of your theme & all required template tags are already in place. Thus, it will be easier for you to style the template later.

Here’s how khổng lồ upload your template files:

Once you’ve sầu gained access to your trang web storage, locate the thư mục of your currently active sầu theme. In our case, it is the Twenty Seventeen theme. So the directory is /public_html/wp-content/themes/twentyseventeen.Copy the single.php & archive sầu.php files và paste them outside that folder.Repeat the second and third steps for other custom post type templates.

Once the template files have sầu been uploaded, it’s time lớn display the WordPress custom post types on the front page.

Displaying Custom Post Types on the Front Page

Custom post types are not displayed on the front page by default. That’s why you have sầu to lớn write a new function that calls the set method of WordPress’ WP_Query object. Let’s take a look at the code structure first:

// Hook our custom function lớn the pre_get_posts action hookadd_action( "pre_get_posts", "add_article_to_frontpage" );// Alter the main queryfunction add_article_to_frontpage( $query ) if ( is_home() &và $query->is_main_query() ) $query->set( "post_type", array( "post", "article" ) );return $query;In this function, $query->set() takes two parameters:

The first one is the property you want khổng lồ change. In our case, we want khổng lồ change the post_type.

The second parameter is the array that you want as the value of the post_type property (post & article).

As you can see, the array starts with ‘post’. This is because it is the default post type in WordPress & we still want to include it on the front page. If you only want to display custom posts on the front page, you can remove it.

In this example, we’ll add ‘article’ to the array, meaning that the front page will show all regular posts and all custom article posts.

Now, khổng lồ achieve this, you can paste the code to your theme functions file (functions.php) or to lớn the site-specific plugin that you have created. Again, to lớn prsự kiện any data loss, we’ll be using the second option.

Access your trang web files again và go to the folder of your site-specific plugin (/public_html/wp-content/plugins/my-custom-post-type).Save your changes.

You can visit your website now. All posts from the mặc định & custom post types should be available on the front page.

*

Adding & Displaying WordPress Custom Field

Once you have created a new WordPress custom post type, you might want to add a custom field so you can provide more details about your nội dung.

There are two ways to lớn vày this – using the standard WordPress custom field or a plugin và each has its own advantages và disadvantages. We’ll begin with the default one.

Using WordPress Default Custom Field

WordPress provides us with a built-in tool khổng lồ add a custom field. What’s great, it is pretty easy to lớn use.

Unfortunately, custom fields won’t show up by mặc định on the front-over of your page. To make them visible, you need to lớn insert the_meta() or emang đến get_post_meta() function lớn the theme file that’s responsible for displaying your posts.

Now that we have sầu two post types, we can either edit single.php or single-article.php. It depends on where you want the custom field to be.

Let’s say we want lớn add an Author custom field for the custom articles posts. We’ll need khổng lồ enter the code in single-article.php. Here are the steps:

From your WordPress Dashboard, head lớn Appearance -> Theme Editor -> singe-article.php.Paste one of the following code snippets lớn the tệp tin under that line.the_meta(); – use this code if you want khổng lồ display all available custom fields on a post.echo get_post_meta( $post->ID, ‘key’, TRUE ); – use this code to display a specific custom field. Rethành viên lớn replace the key value with your custom field name.After that, click Update File.

If you visit your website, you will see the Author custom field below the post.

*

Limiting Custom Fields khổng lồ a Specific Post Type via a Plugin

*

While it is simple khổng lồ use, adding custom fields directly from WordPress is not necessarily the best option. That’s because once you’ve added a custom field, it will be available for all types of posts. This can make it difficult khổng lồ find the field you need for a specific post type.

Therefore, you might want lớn try the Advanced Custom Fields plugin. It limits certain custom fields so that they are only selectable on a chosen post type. This is how you use the tool:

There will be a new menu on your sidebar called Custom Fields. To add a custom field, cliông xã the Add New button. You will need to enter several important details, such as:Field Label – the name of your custom field that will be displayed on the edit page.

Xem thêm: Cách Ghép Ảnh Cô Dâu Trên Điện Thoại Android, Iphone, Samsung S8, Oppo

Field Name – the ID of your custom field that will be used to display on your theme.Once you’re done, hit Cthua trận Field. Now, to limit this custom field khổng lồ a specific post type, head to lớn the Location settings in Advanced Custom Field plugin.