卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16869本站已运行3321

使用自定义帖子类型通过 WordPress 创建自定义常见问题解答系统

使用自定义帖子类型通过 WordPress 创建自定义常见问题解答系统

我最近与我的一位客户合作,她在她的工作领域担任专业顾问。她问我是否可以实施一个问答系统,确切地说是一个常见问题解答页面。我说,“当然,我们可以创建一个页面,然后用不同的样式粘贴问题和答案”,但她说她会创建不同的页面并对问题和答案进行分类,为了更有条理,她需要一个不同的方法。

为此,我将向您展示如何使用自定义帖子类型、分类法和短代码,通过几行简单的代码来处理她的请求。

自定义帖子类型和分类

建立常见问题解答系统需要什么?

  • 我们需要用于问题和答案的字段。
  • 我们需要类别来对不同类型的问题及其答案进行分类和区分。
  • 在我们的例子中,我们需要一个短代码来将这些问题组或所有问题嵌入到页面或帖子中。

让我们首先创建自定义帖子类型。

第 1 步:创建自定义帖子类型

当然,我们首先会为常见问题解答项目设置自定义帖子类型。我们将在 register_post_type() 函数的帮助下创建一个新的自定义帖子类型,但是如果您想要一个用于创建帖子类型的 GUI,您可以使用GenerateWP 的帖子类型生成器工具生成它,就像我在这个例子:

<?php

if ( ! function_exists( \'tuts_faq_cpt\' ) ) {

// register custom post type
	function tuts_faq_cpt() {

		// these are the labels in the admin interface, edit them as you like
		$labels = array(
			\'name\'                => _x( \'FAQs\', \'Post Type General Name\', \'tuts_faq\' ),
			\'singular_name\'       => _x( \'FAQ\', \'Post Type Singular Name\', \'tuts_faq\' ),
			\'menu_name\'           => __( \'FAQ\', \'tuts_faq\' ),
			\'parent_item_colon\'   => __( \'Parent Item:\', \'tuts_faq\' ),
			\'all_items\'           => __( \'All Items\', \'tuts_faq\' ),
			\'view_item\'           => __( \'View Item\', \'tuts_faq\' ),
			\'add_new_item\'        => __( \'Add New FAQ Item\', \'tuts_faq\' ),
			\'add_new\'             => __( \'Add New\', \'tuts_faq\' ),
			\'edit_item\'           => __( \'Edit Item\', \'tuts_faq\' ),
			\'update_item\'         => __( \'Update Item\', \'tuts_faq\' ),
			\'search_items\'        => __( \'Search Item\', \'tuts_faq\' ),
			\'not_found\'           => __( \'Not found\', \'tuts_faq\' ),
			\'not_found_in_trash\'  => __( \'Not found in Trash\', \'tuts_faq\' ),
		);
		$args = array(
			// use the labels above
			\'labels\'              => $labels,
			// we\'ll only need the title, the Visual editor and the excerpt fields for our post type
			\'supports\'            => array( \'title\', \'editor\', \'excerpt\', ),
			// we\'re going to create this taxonomy in the next section, but we need to link our post type to it now
			\'taxonomies\'          => array( \'tuts_faq_tax\' ),
			// make it public so we can see it in the admin panel and show it in the front-end
			\'public\'              => true,
			// show the menu item under the Pages item
			\'menu_position\'       => 20,
			// show archives, if you don\'t need the shortcode
			\'has_archive\'         => true,
		);
		register_post_type( \'tuts_faq\', $args );

	}

	// hook into the \'init\' action
	add_action( \'init\', \'tuts_faq_cpt\', 0 );

}

?>

提示:如果您的项目将涉及更多自定义帖子类型,这些类型可能比这个简单的常见问题解答帖子类型更复杂,我可以推荐一个名为 SuperCPT 的酷工具,它允许您创建新帖子类型具有更简单的代码。我也写了一篇关于SuperCPT的教程,你可以在这里查看。

第 2 步:创建自定义分类

为了区分不同类型的问题(例如我的客户关于流产和产后抑郁症的问题和答案),我们需要一个类别系统。正如你们许多人已经知道的那样,WordPress 通过自定义分类法提供了此功能。

这里的基本函数是 register_taxonomy() 但同样,如果您需要图形界面,您可以使用GenerateWP 的分类生成器工具。

代码如下:

<?php

if ( ! function_exists( \'tuts_faq_tax\' ) ) {

	// register custom taxonomy
	function tuts_faq_tax() {

		// again, labels for the admin panel
		$labels = array(
			\'name\'                       => _x( \'FAQ Categories\', \'Taxonomy General Name\', \'tuts_faq\' ),
			\'singular_name\'              => _x( \'FAQ Category\', \'Taxonomy Singular Name\', \'tuts_faq\' ),
			\'menu_name\'                  => __( \'FAQ Categories\', \'tuts_faq\' ),
			\'all_items\'                  => __( \'All FAQ Cats\', \'tuts_faq\' ),
			\'parent_item\'                => __( \'Parent FAQ Cat\', \'tuts_faq\' ),
			\'parent_item_colon\'          => __( \'Parent FAQ Cat:\', \'tuts_faq\' ),
			\'new_item_name\'              => __( \'New FAQ Cat\', \'tuts_faq\' ),
			\'add_new_item\'               => __( \'Add New FAQ Cat\', \'tuts_faq\' ),
			\'edit_item\'                  => __( \'Edit FAQ Cat\', \'tuts_faq\' ),
			\'update_item\'                => __( \'Update FAQ Cat\', \'tuts_faq\' ),
			\'separate_items_with_commas\' => __( \'Separate items with commas\', \'tuts_faq\' ),
			\'search_items\'               => __( \'Search Items\', \'tuts_faq\' ),
			\'add_or_remove_items\'        => __( \'Add or remove items\', \'tuts_faq\' ),
			\'choose_from_most_used\'      => __( \'Choose from the most used items\', \'tuts_faq\' ),
			\'not_found\'                  => __( \'Not Found\', \'tuts_faq\' ),
		);
		$args = array(
			// use the labels above
			\'labels\'                     => $labels,
			// taxonomy should be hierarchial so we can display it like a category section
			\'hierarchical\'               => true,
			// again, make the taxonomy public (like the post type)
			\'public\'                     => true,
		);
		// the contents of the array below specifies which post types should the taxonomy be linked to
		register_taxonomy( \'tuts_faq_tax\', array( \'tuts_faq\' ), $args );

	}

	// hook into the \'init\' action
	add_action( \'init\', \'tuts_faq_tax\', 0 );

}

?>

就是这样!现在您有了一个常见问题解答帖子类型,其中的分类法称为“常见问题解答类别”,相互链接!检查您的管理面板,您将在“常见问题解答”下看到“常见问题解答类别”菜单项。

就像常规帖子类别一样,您可以在“常见问题解答类别”页面中添加、编辑或删除它们,也可以在编写新的常见问题解答项目时添加新类别。

第 3 步:创建 [faq] 简码

有趣的部分来了:构建短代码。 (如果您读过我之前的帖子,您就会知道我是 WordPress 短代码的忠实粉丝。)我们基本上会将常见问题解答项目嵌入到帖子和页面中。

接下来会发生什么:

  • 在我们新的自定义帖子类型中查询,
  • 使用短代码参数过滤其类别,
  • 将问题和答案显示为标题和内容,
  • 通过“更多...”链接显示答案摘录,由另一个短代码参数控制。

让我们开始构建短代码。与上面的代码一样,我将添加一些有用的注释:

<?php

if ( ! function_exists( \'tuts_faq_shortcode\' ) ) {

	function tuts_faq_shortcode( $atts ) {
		extract( shortcode_atts(
				array(
					// category slug attribute - defaults to blank
					\'category\' => \'\',
					// full content or excerpt attribute - defaults to full content
					\'excerpt\' => \'false\',
				), $atts )
		);
		
		$output = \'\';
		
		// set the query arguments
		$query_args = array(
			// show all posts matching this query
			\'posts_per_page\'	=>	-1,
			// show the \'tuts_faq\' custom post type
			\'post_type\'			=>	\'tuts_faq\',
			// show the posts matching the slug of the FAQ category specified with the shortcode\'s attribute
			\'tax_query\'			=>	array(
				array(
					\'taxonomy\'	=>	\'tuts_faq_tax\',
					\'field\'		=>	\'slug\',
					\'terms\'		=>	$category,
				)
			),
			// tell WordPress that it doesn\'t need to count total rows - this little trick reduces load on the database if you don\'t need pagination
			\'no_found_rows\'		=>	true,
		);
		
		// get the posts with our query arguments
		$faq_posts = get_posts( $query_args );
		$output .= \'<div class="tuts-faq">\';
		
		// handle our custom loop
		foreach ( $faq_posts as $post ) {
			setup_postdata( $post );
			$faq_item_title = get_the_title( $post->ID );
			$faq_item_permalink = get_permalink( $post->ID );
			$faq_item_content = get_the_content();
			if( $excerpt == \'true\' )
				$faq_item_content = get_the_excerpt() . \'<a href="\' . $faq_item_permalink . \'">\' . __( \'More...\', \'tuts_faq\' ) . \'</a>\';
			
			$output .= \'<div class="tuts-faq-item">\';
			$output .= \'<h3 class="tuts-faq-item-title">\' . $faq_item_title . \'</h3>\';
			$output .= \'<div class="tuts-faq-item-content">\' . $faq_item_content . \'</div>\';
			$output .= \'</div>\';
		}
		
		wp_reset_postdata();
		
		$output .= \'</div>\';
		
		return $output;
	}

	add_shortcode( \'faq\', \'tuts_faq_shortcode\' );

}

?>

就是这样!现在我们有一个简洁的短代码来嵌入我们的问题和答案。您可以使用类名 tuts-faqtuts-faq-itemtuts-faq-item-titletuts-faq-item-content 对其进行样式设置。不过,即使您不包含额外的样式,也应该没问题。

第 4 步:总结代码

由于这些代码不仅涉及前端样式,还引入新功能,因此它算作插件领域。这就是为什么我们必须将代码保存为插件。当我们这样做时,我们还应该在激活和停用时刷新重写规则。

完整代码如下:

<?php
/*
Plugin Name: Simple FAQ System
Plugin URI: http://code.tutsplus.com/
Description: Helps you create an FAQ section for your WordPress website. Shortcode usage: [faq]
Version: 1.0
Author: Barış Ünver
Author URI: http://hub.tutsplus.com/authors/baris-unver
License: Public Domain
*/

if ( ! function_exists( \'tuts_faq_cpt\' ) ) {

// register custom post type
	function tuts_faq_cpt() {

		// these are the labels in the admin interface, edit them as you like
		$labels = array(
			\'name\'                => _x( \'FAQs\', \'Post Type General Name\', \'tuts_faq\' ),
			\'singular_name\'       => _x( \'FAQ\', \'Post Type Singular Name\', \'tuts_faq\' ),
			\'menu_name\'           => __( \'FAQ\', \'tuts_faq\' ),
			\'parent_item_colon\'   => __( \'Parent Item:\', \'tuts_faq\' ),
			\'all_items\'           => __( \'All Items\', \'tuts_faq\' ),
			\'view_item\'           => __( \'View Item\', \'tuts_faq\' ),
			\'add_new_item\'        => __( \'Add New FAQ Item\', \'tuts_faq\' ),
			\'add_new\'             => __( \'Add New\', \'tuts_faq\' ),
			\'edit_item\'           => __( \'Edit Item\', \'tuts_faq\' ),
			\'update_item\'         => __( \'Update Item\', \'tuts_faq\' ),
			\'search_items\'        => __( \'Search Item\', \'tuts_faq\' ),
			\'not_found\'           => __( \'Not found\', \'tuts_faq\' ),
			\'not_found_in_trash\'  => __( \'Not found in Trash\', \'tuts_faq\' ),
		);
		$args = array(
			// use the labels above
			\'labels\'              => $labels,
			// we\'ll only need the title, the Visual editor and the excerpt fields for our post type
			\'supports\'            => array( \'title\', \'editor\', \'excerpt\', ),
			// we\'re going to create this taxonomy in the next section, but we need to link our post type to it now
			\'taxonomies\'          => array( \'tuts_faq_tax\' ),
			// make it public so we can see it in the admin panel and show it in the front-end
			\'public\'              => true,
			// show the menu item under the Pages item
			\'menu_position\'       => 20,
			// show archives, if you don\'t need the shortcode
			\'has_archive\'         => true,
		);
		register_post_type( \'tuts_faq\', $args );

	}

	// hook into the \'init\' action
	add_action( \'init\', \'tuts_faq_cpt\', 0 );

}

if ( ! function_exists( \'tuts_faq_tax\' ) ) {

	// register custom taxonomy
	function tuts_faq_tax() {

		// again, labels for the admin panel
		$labels = array(
			\'name\'                       => _x( \'FAQ Categories\', \'Taxonomy General Name\', \'tuts_faq\' ),
			\'singular_name\'              => _x( \'FAQ Category\', \'Taxonomy Singular Name\', \'tuts_faq\' ),
			\'menu_name\'                  => __( \'FAQ Categories\', \'tuts_faq\' ),
			\'all_items\'                  => __( \'All FAQ Cats\', \'tuts_faq\' ),
			\'parent_item\'                => __( \'Parent FAQ Cat\', \'tuts_faq\' ),
			\'parent_item_colon\'          => __( \'Parent FAQ Cat:\', \'tuts_faq\' ),
			\'new_item_name\'              => __( \'New FAQ Cat\', \'tuts_faq\' ),
			\'add_new_item\'               => __( \'Add New FAQ Cat\', \'tuts_faq\' ),
			\'edit_item\'                  => __( \'Edit FAQ Cat\', \'tuts_faq\' ),
			\'update_item\'                => __( \'Update FAQ Cat\', \'tuts_faq\' ),
			\'separate_items_with_commas\' => __( \'Separate items with commas\', \'tuts_faq\' ),
			\'search_items\'               => __( \'Search Items\', \'tuts_faq\' ),
			\'add_or_remove_items\'        => __( \'Add or remove items\', \'tuts_faq\' ),
			\'choose_from_most_used\'      => __( \'Choose from the most used items\', \'tuts_faq\' ),
			\'not_found\'                  => __( \'Not Found\', \'tuts_faq\' ),
		);
		$args = array(
			// use the labels above
			\'labels\'                     => $labels,
			// taxonomy should be hierarchial so we can display it like a category section
			\'hierarchical\'               => true,
			// again, make the taxonomy public (like the post type)
			\'public\'                     => true,
		);
		// the contents of the array below specifies which post types should the taxonomy be linked to
		register_taxonomy( \'tuts_faq_tax\', array( \'tuts_faq\' ), $args );

	}

	// hook into the \'init\' action
	add_action( \'init\', \'tuts_faq_tax\', 0 );

}

if ( ! function_exists( \'tuts_faq_shortcode\' ) ) {

	function tuts_faq_shortcode( $atts ) {
		extract( shortcode_atts(
				array(
					// category slug attribute - defaults to blank
					\'category\' => \'\',
					// full content or excerpt attribute - defaults to full content
					\'excerpt\' => \'false\',
				), $atts )
		);
		
		$output = \'\';
		
		// set the query arguments
		$query_args = array(
			// show all posts matching this query
			\'posts_per_page\'	=>	-1,
			// show the \'tuts_faq\' custom post type
			\'post_type\'			=>	\'tuts_faq\',
			// show the posts matching the slug of the FAQ category specified with the shortcode\'s attribute
			\'tax_query\'			=>	array(
				array(
					\'taxonomy\'	=>	\'tuts_faq_tax\',
					\'field\'		=>	\'slug\',
					\'terms\'		=>	$category,
				)
			),
			// tell WordPress that it doesn\'t need to count total rows - this little trick reduces load on the database if you don\'t need pagination
			\'no_found_rows\'		=>	true,
		);
		
		// get the posts with our query arguments
		$faq_posts = get_posts( $query_args );
		$output .= \'<div class="tuts-faq">\';
		
		// handle our custom loop
		foreach ( $faq_posts as $post ) {
			setup_postdata( $post );
			$faq_item_title = get_the_title( $post->ID );
			$faq_item_permalink = get_permalink( $post->ID );
			$faq_item_content = get_the_content();
			if( $excerpt == \'true\' )
				$faq_item_content = get_the_excerpt() . \'<a href="\' . $faq_item_permalink . \'">\' . __( \'More...\', \'tuts_faq\' ) . \'</a>\';
			
			$output .= \'<div class="tuts-faq-item">\';
			$output .= \'<h2 class="faq-item-title">\' . $faq_item_title . \'</h2>\';
			$output .= \'<div class="faq-item-content">\' . $faq_item_content . \'</div>\';
			$output .= \'</div>\';
		}
		
		wp_reset_postdata();
		
		$output .= \'</div>\';
		
		return $output;
	}

	add_shortcode( \'faq\', \'tuts_faq_shortcode\' );

}

function tuts_faq_activate() {
	tuts_faq_cpt();
	flush_rewrite_rules();
}

register_activation_hook( __FILE__, \'tuts_faq_activate\' );

function tuts_faq_deactivate() {
	flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, \'tuts_faq_deactivate\' );

?>

改进空间

当我向我的客户展示如何使用它时,她对结果很满意。但在这里,我们可以使用更多功能扩展代码,例如...

  1. 手风琴效果:如果您想通过一些切换效果使常见问题解答部分更具吸引力,您可以使用一些很棒的 jQuery 插件。如果您想使用 jQuery UI,Shane Osbourne 提供了一个很棒的教程,介绍了如何使用。
  2. 分页:如果您对某个类别有很多问题和答案,并且不想一次显示所有项目,您可以通过更改 posts_per_page 参数来限制帖子数量自定义短代码的查询,并使用 wp_reset_postdata(); 代码在行下方添加分页链接所需的代码。请记住删除 \'no_found_rows\' => true, 行,但如果不删除它,分页将无法工作!
  3. 随机问题:假设您想在主页上显示一个随机问题和答案,并且希望它在每次页面刷新时进行更改。您需要做的就是前往自定义查询,将 posts_per_page 参数从 -1 更改为 1 并添加另一行代码 \'orderby\' => \'random\', 和你\'一切顺利!

结论

这就是您如何通过使用自定义帖子类型、自定义分类法和短代码在 WordPress 中构建简单的常见问题解答系统。我希望您喜欢本教程,并且可以在下一个项目中使用它。如果您喜欢这篇文章,请不要忘记分享它!

您对改进此常见问题解答系统有什么想法吗?在下面分享您的评论!

卓越飞翔博客
上一篇: 形成给定字符串所需的最小前缀和后缀的数量
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏