wordpress 自定义_如何在WordPress中创建自定义帖子类型

wordpress 自定义

Do you want to learn how to easily create custom post types in WordPress? Custom post types transform a WordPress site from a blogging platform into a powerful Content Management System (CMS).

您是否想学习如何在WordPress中轻松创建自定义帖子类型? 自定义帖子类型将WordPress网站从博客平台转变为功能强大的内容管理系统( CMS )。

Basically, they allow you to go beyond posts and pages by creating different content types for your website.

基本上,它们允许您通过为网站创建不同的内容类型来超越帖子和页面。

In this article, we’ll show you how to easily create custom post types in WordPress. We’ll teach you two methods and you can choose one that looks easier to you.

在本文中,我们将向您展示如何轻松地在WordPress中创建自定义帖子类型。 我们将教您两种方法,您可以选择一种看起来更简单的方法。

Creating custom post types in WordPress
WordPress中的自定义帖子类型是什么? (What is Custom Post Type in WordPress?)

Custom post types are content types like posts and pages. Since WordPress evolved from a simple blogging platform into a robust CMS, the term post stuck to it. However, a post type can be any kind of content.

自定义帖子类型是诸如帖子和页面之类的内容类型。 由于WordPress从简单的博客平台演变为功能强大的CMS,术语post一直坚持下去。 但是,帖子类型可以是任何种类的内容。

By default, WordPress comes with these post types:

默认情况下,WordPress随附以下帖子类型:

  • Post

    发布
  • Page

  • Attachment

    附件
  • Revision

    修订版
  • Nav Menu

    导航菜单

You can create your own custom post types and call them whatever you want.

您可以创建自己的自定义帖子类型,然后根据需要调用它们。

For instance, if you run a movie review website, then you would probably want to create a movie reviews post type. This post type can have different custom fields and even its own custom category structure.

例如,如果您运行一个电影评论网站,则可能要创建一个电影评论帖子类型。 该帖子类型可以具有不同的自定义字段,甚至可以具有其自己的自定义类别结构。

Other examples of post types are Portfolio, Testimonials, Products, etc.

职位类型的其他示例包括投资组合,推荐书,产品等。

Many popular WordPress plugins already use custom post types to store data on your WordPress website. The following are a few top plugins that use custom post types.

许多流行的WordPress插件已经使用自定义帖子类型将数据存储在WordPress网站上。 以下是一些使用自定义帖子类型的顶级插件。

  • WooCommerce – Adds a product custom post type to your WordPress site.WooCommerce –将产品自定义帖子类型添加到您的WordPress网站。
  • WPForms – Creates a wpforms post type to store all your formsWPForms –创建wpforms帖子类型以存储所有表单
  • MemberPress – Adds a memberpressproduct custom post typeMemberPress –添加memberpressproduct自定义帖子类型

When do I need a custom post type?

我什么时候需要自定义帖子类型?

Check out our article about when do you really need custom post types or taxonomies in WordPress.

查看我们的文章,了解何时真正需要WordPress中的自定义帖子类型或分类法

Also take a look at WPBeginner’s Deals and Glossary sections. These are custom post types that we created to keep these sections separate from our daily blog articles. It helps us better organize our website content.

还可以查看WPBeginner的“ 交易”和“ 词汇表”部分。 这些是我们创建的自定义帖子类型,以使这些部分与我们的日常博客文章分开。 它可以帮助我们更好地组织网站内容。

You will also notice that we are using custom taxonomies for them instead of categories or tags.

您还将注意到,我们正在为其使用自定义分类法 ,而不是类别或标签。

That being said, let’s take a look at how to easily create custom post types in WordPress for your own use.

话虽如此,让我们看一下如何轻松地在WordPress中创建自定义帖子类型以供您自己使用。

方法1.创建自定义帖子类型–简单方法 (Method 1. Creating a Custom Post Type – The Easy Way)

The easiest way to create a custom post type in WordPress is by using a plugin. This method is recommended for beginners because it is safe and super easy.

在WordPress中创建自定义帖子类型的最简单方法是使用插件。 推荐给初学者使用此方法,因为它安全且超级容易。

The first thing you need to do is install and activate the Custom Post Type UI plugin. Upon activation, the plugin will add a new menu item in your WordPress admin menu called CPT UI.

您需要做的第一件事是安装并激活“ 自定义帖子类型” UI插件。 激活后,该插件将在您的WordPress管理菜单中添加一个名为CPT UI的新菜单项。

Now go to CPT UI » Add New to create a new custom post type.

现在转到CPT UI»添加新内容以创建新的自定义帖子类型。

Add new custom post type

First, you need to provide a slug for your custom post type. This slug will be used in the URL and in WordPress queries, so it can only contain letters and numbers.

首先,您需要为自定义帖子类型提供一个标签。 这蛞蝓将在URL和在WordPress查询中使用,所以它只能包含字母和数字。

Below that, you need to provide the plural and singular names for your custom post type.

在此之下,您需要为自定义帖子类型提供复数和单数名称。

Next, you can optionally click on the link that says ‘Populate additional labels based on chosen labels’. Doing so will fill in the rest of the label fields down below.

接下来,您可以选择单击“根据所选标签填充其他标签”链接。 这样做将在下面填充其余的标签字段。

Scroll down to the ‘Additional Labels’ section and from here you can provide a description for your post type and change labels.

向下滚动到“其他标签”部分,然后您可以在此处提供有关帖子类型和更改标签的描述。

Post type labels

Labels will be used throughout the WordPress user interface when you are managing content in that particular post type.

当您管理特定帖子类型的内容时,将在整个WordPress用户界面中使用标签。

Next, comes the post type settings option. From here you can set up different attributes for your post type. Each option comes with a brief description explaining what it does.

接下来是帖子类型设置选项。 在这里,您可以为帖子类型设置不同的属性。 每个选项都带有简要说明,说明其功能。

Post type settings

For instance, you can choose not to make a post type hierarchical like pages or reverse chronological like posts.

例如,您可以选择不对帖子类型进行分层(如页面)或按时间顺序进行逆序排序(如帖子)。

Below the general settings, you will see the option to select which editing features this post type would support. Simply check the options that you want to be included.

在常规设置下方,您将看到用于选择此帖子类型将支持哪些编辑功能的选项。 只需检查您想要包含的选项。

Supported options

Finally, click on the ‘Add Post Type’ button to save and create your custom post type.

最后,点击“添加帖子类型”按钮以保存并创建您的自定义帖子类型。

That’s all, you have successfully created your custom post type. You can go ahead and start adding content.

就是这样,您已经成功创建了自定义帖子类型。 您可以继续并开始添加内容。

We will show you how to display your custom post type on your website later in this article.

本文稍后将向您展示如何在您的网站上显示自定义帖子类型。

手动创建自定义帖子类型 (Creating a Custom Post Type Manually)

The problem with using a plugin is that your custom post types will disappear when the plugin is deactivated. Any data you have in those custom post types will still be there, but your custom post type will be unregistered and will not be accessible from the admin area.

使用插件的问题在于,停用插件后,您的自定义帖子类型将消失。 您在这些自定义帖子类型中拥有的所有数据仍将在那里,但是您的自定义帖子类型将被取消注册,并且无法从管理区域访问。

If you are working on a client site and do not want to install another plugin, then you can manually create your custom post type by adding the required code in your theme’s functions.php file or in a site-specific plugin (See: Custom Post Types Debate functions.php or Plugin).

如果您在客户端站点上工作并且不想安装其他插件,则可以通过在主题的functions.php文件或特定站点的插件中添加所需的代码来手动创建自定义帖子类型(请参阅: 自定义帖子)输入Debate functions.php或Plugin )。

First, we will show you a quick and fully working example so that you understand how it works. Take a look at this code:

首先,我们将向您展示一个快速且完整的示例,以便您了解其工作原理。 看一下这段代码:


// Our custom post type function
function create_posttype() {

	register_post_type( 'movies',
	// CPT Options
		array(
			'labels' => array(
				'name' => __( 'Movies' ),
				'singular_name' => __( 'Movie' )
			),
			'public' => true,
			'has_archive' => true,
			'rewrite' => array('slug' => 'movies'),
			'show_in_rest' => true,

		)
	);
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );

What this code does is that it registers a post type 'movies' with an array of arguments. These arguments are the options of our custom post type.

该代码的作用是它注册带有数组参数的帖子类型'movies' 。 这些参数是我们自定义帖子类型的选项。

This array has two parts, the first part is labeled, which itself is an array. The second part contains other arguments like public visibility, has archive, slug, and show_in_rest enables block editor support.

这个数组有两个部分,第一部分被标记,它本身就是一个数组。 第二部分包含其他参数,例如公共可见性,具有存档,段位和show_in_rest启用块编辑器支持。

Now let’s take a look at a detailed piece of code that adds more options to your custom post type.

现在,让我们看一下一段详细的代码,为您的自定义帖子类型添加更多选项。



/*
* Creating a function to create our CPT
*/

function custom_post_type() {

// Set UI labels for Custom Post Type
	$labels = array(
		'name'                => _x( 'Movies', 'Post Type General Name', 'twentytwenty' ),
		'singular_name'       => _x( 'Movie', 'Post Type Singular Name', 'twentytwenty' ),
		'menu_name'           => __( 'Movies', 'twentytwenty' ),
		'parent_item_colon'   => __( 'Parent Movie', 'twentytwenty' ),
		'all_items'           => __( 'All Movies', 'twentytwenty' ),
		'view_item'           => __( 'View Movie', 'twentytwenty' ),
		'add_new_item'        => __( 'Add New Movie', 'twentytwenty' ),
		'add_new'             => __( 'Add New', 'twentytwenty' ),
		'edit_item'           => __( 'Edit Movie', 'twentytwenty' ),
		'update_item'         => __( 'Update Movie', 'twentytwenty' ),
		'search_items'        => __( 'Search Movie', 'twentytwenty' ),
		'not_found'           => __( 'Not Found', 'twentytwenty' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'twentytwenty' ),
	);
	
// Set other options for Custom Post Type
	
	$args = array(
		'label'               => __( 'movies', 'twentytwenty' ),
		'description'         => __( 'Movie news and reviews', 'twentytwenty' ),
		'labels'              => $labels,
		// Features this CPT supports in Post Editor
		'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
		// You can associate this CPT with a taxonomy or custom taxonomy. 
		'taxonomies'          => array( 'genres' ),
		/* A hierarchical CPT is like Pages and can have
		* Parent and child items. A non-hierarchical CPT
		* is like Posts.
		*/	
		'hierarchical'        => false,
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'post',
		'show_in_rest' => true,

	);
	
	// Registering your Custom Post Type
	register_post_type( 'movies', $args );

}

/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/

add_action( 'init', 'custom_post_type', 0 );


As you can see, we have added many more options to the custom post type with this code. It will add more features like support for revisions, featured image, custom fields, and more.

如您所见,我们使用此代码为自定义帖子类型添加了更多选项。 它将添加更多功能,例如对修订的支持,特色图片,自定义字段等。

We have also associated this custom post type with a custom taxonomy called genres.

我们还将这种自定义帖子类型与一种称为流派的自定义分类法相关联。

You may also notice the part where we have set the hierarchical value to be false. If you would like your custom post type to behave like Pages, then you can set this value to true.

您可能还会注意到我们将层次结构值设置为false的部分。 如果您希望自定义帖子类型的行为类似于Pages,则可以将此值设置为true。

Another thing to be noticed is the repeated usage of twentytwenty string, this is called text-domain. If your theme is translation ready, and you want your custom post types to be translated, then you will need to mention text domain used by your theme.

要注意的另一件事是重复使用二十二十个字符串,这称为文本域。 如果您的主题已准备好翻译 ,并且您希望翻译自定义帖子类型,那么您将需要提及主题使用的文本域。

You can find your theme’s text domain inside style.css file in your theme directory. The text domain will be mentioned in the header of the file.

您可以在主题目录的style.css文件中找到主题的文本域。 文本域将在文件标题中提及。

在您的网站上显示自定义帖子类型 (Displaying Custom Post Types on Your Site)

WordPress comes with built-in support for displaying your custom post types. Once you have added a few items into your new custom post type, it is time to display them on your website.

WordPress内置支持显示自定义帖子类型的功能。 将一些项目添加到新的自定义帖子类型后,就可以在网站上显示它们了。

There are a couple of methods that you can use, each one has its own benefits.

您可以使用两种方法,每种方法都有其自身的优势。

使用默认存档模板显示自定义帖子类型 (Displaying Custom Post Type Using Default Archive Template)

First, you can simply go to Appearance » Menus and add a custom link to your menu. This custom link is the link to your custom post type.

首先,您只需转到外观»菜单 ,然后向菜单添加自定义链接。 该自定义链接是指向您的自定义帖子类型的链接。

Add post type to your navigation menu

If you are using SEO friendly permalinks then your CPT’s URL will most likely be something like this:

如果您使用的是SEO友好的永久链接,那么CPT的URL很可能是这样的:

http://example.com/movies

http://example.com/movies

If you are not using SEO friendly permalinks, then your custom post type URL will be something like this:

如果您没有使用SEO友好的永久链接 ,则您的自定义帖子类型URL将如下所示:

http://example.com/?post_type=movies

http://example.com/?post_type=movies

Don’t forget to replace example.com with your own domain name and movies with your custom post type name.

不要忘记用您自己的域名替换example.com,并用您的自定义帖子类型名称替换电影。

Save your menu and then visit the front-end of your website. You will see the new menu you added, and when you click on it, it will display your custom post type archive page using the archive.php template file in your theme.

保存菜单,然后访问网站的前端。 您将看到添加的新菜单,然后单击该菜单,它将使用主题中的archive.php 模板文件显示自定义帖子类型存档页面。

对CPT存档和单个条目使用自定义模板 (Using Custom Templates for CPT Archives and Single Entries)

If you don’t like the appearance of the archive page for your custom post type, then you can use dedicated template for custom post type archive.

如果您不喜欢自定义帖子类型的存档页面外观,则可以使用专用模板作为自定义帖子类型的存档

To do that all you need to do is create a new file in your theme directory and name it archive-movies.php. Replace movies with the name of your custom post type.

为此,您需要做的就是在主题目录中创建一个新文件,并将其命名为archive-movies.php 。 用自定义帖子类型的名称替换电影。

For getting started, you can copy the contents of your theme’s archive.php file into archive-movies.php template and then start modifying it to meet your needs.

首先,您可以将主题的archive.php文件的内容复制到archive-movies.php模板中,然后开始对其进行修改以满足您的需求。

Now whenever the archive page for your custom post type is accessed, this template will be used to display it.

现在,无论何时访问自定义帖子类型的存档页面,都将使用此模板来显示它。

Similarly, you can also create a custom template for your post type’s single entry display. To do that you need to create single-movies.php in your theme directory. Don’t forget to replace movies with the name of your custom post type.

同样,您也可以为帖子类型的单项显示创建自定义模板。 为此,您需要在主题目录中创建single-movies.php 。 不要忘记用自定义帖子类型的名称替换电影。

You can get started by copying the contents of your theme’s single.php template into single-movies.php template and then start modifying it to meet your needs.

您可以通过将主题的single.php模板的内容复制到single-movies.php模板开始,然后开始对其进行修改以满足您的需求。

在首页上显示自定义帖子类型 (Displaying Custom Post Types on The Front Page)

One advantage of using custom post types is that it keeps your custom content types away from your regular posts. However, if you would like them to display among your regular post, then you can do so by adding this code into your theme’s functions.php file or a site-specific plugin:

使用自定义帖子类型的一个优点是,它可以使您的自定义内容类型远离常规帖子。 但是,如果希望它们显示在常规帖子中,则可以通过将以下代码添加到主题的functions.php文件或特定于站点的插件中来实现:


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', 'movies' ) );
	return $query;
}

Don’t forget to replace movies with your custom post type.

不要忘了用自定义帖子类型替换movies

查询自定义帖子类型 (Querying Custom Post Types)

If you are familiar with the coding and would like to run loop queries in your templates, then here is how to do that (Related: What is a Loop?).

如果您熟悉编码并想在模板中运行循环查询,那么这里是执行该操作的方法(相关内容: 什么是循环? )。

By querying the database, you can retrieve items from a custom post type.

通过查询数据库,您可以从自定义帖子类型检索项目。


<?php 
$args = array( 'post_type' => 'movies', 'posts_per_page' => 10 );
$the_query = new WP_Query( $args ); 
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<div class="entry-content">
<?php the_content(); ?> 
</div>
<?php wp_reset_postdata(); ?>
<?php else:  ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

In this code, first, we have defined the post type and posts per page in the arguments for our new WP_Query class.

在此代码中,首先,我们在新的WP_Query类的参数中定义了帖子类型和每页帖子数。

After that, we ran our query, retrieved the posts and displayed them inside the loop.

之后,我们运行查询,检索帖子并将其显示在循环中。

在窗口小部件中显示自定义帖子类型 (Displaying Custom Post Types in Widgets)

You will notice that there is a default widget in WordPress to display recent posts, but it does not allow you to choose a custom post type.

您会注意到WordPress中有一个默认的小部件来显示最近的帖子,但是它不允许您选择自定义帖子类型。

What if you wanted to display the latest entries from your newly created post type in a widget? There is an easy way to do this.

如果要在小部件中显示新创建的帖子类型的最新条目怎么办? 有一个简单的方法可以做到这一点。

First thing you need to do is install and activate the Ultimate Posts Widget plugin. Upon activation, simply go to Appearance » Widgets and drag and drop the Ultimate Posts widget to a sidebar.

您需要做的第一件事是安装并激活Ultimate Posts Widget插件。 激活后,只需转到外观»小部件,然后将Ultimate Posts小部件拖放到侧栏。

Ultimate posts widget

This powerful widget will allow you to show recent posts from any post types. You can also display post excerpts with a read more link or even show a featured image next to post title.

这个强大的小部件可让您显示任何帖子类型的最新帖子。 您还可以显示带有更多链接的文章摘录,甚至在文章标题旁边显示特色图片。

Configure the widget by selecting the options you want and by selecting your custom post type. After that save your changes and see the widget in action on your website.

通过选择所需的选项并选择自定义帖子类型来配置窗口小部件。 之后,保存您的更改,并在您的网站上查看运行中的小部件。

更多高级自定义帖子类型调整 (More Advance Custom Post Type Tweaks)

There is so much more you can do with your custom post types. You can learn to add your custom post types in main RSS feed or create a separate feed for each custom post type.

您可以使用自定义帖子类型做更多的事情。 您可以学习在主RSS feed中添加自定义帖子类型,为每种自定义帖子类型创建单独的feed

For more hacks, see our list of the most useful WordPress custom post types tutorials.

有关更多技巧,请参阅我们最有用的WordPress自定义帖子类型教程列表

If you’re looking for a no-code solution to customize your custom post type archive pages, then we recommend taking a look at a WordPress page builder plugin like Beaver Builder or Divi because they both can help you do that.

如果您正在寻找一种无需代码的解决方案来自定义自定义帖子类型存档页面,那么我们建议您看一下Beaver BuilderDivi之类的WordPress页面构建器插件,因为它们都可以帮助您做到这一点。

We hope this article helped you learn how to create custom post types in WordPress. You may also want to see our guide on how to increase your website traffic with practical tips.

我们希望本文能帮助您学习如何在WordPress中创建自定义帖子类型。 您可能还希望参阅实用指南,了解如何增加网站流量的指南。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

如果您喜欢这篇文章,请订阅我们的YouTube频道 WordPress视频教程。 您也可以在TwitterFacebook上找到我们。

翻译自: https://www.wpbeginner.com/wp-tutorials/how-to-create-custom-post-types-in-wordpress/

wordpress 自定义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值