搜索
首页后端开发php教程使用自定义帖子类型通过 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 id="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: <code>[faq]</code>
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 id="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 中构建简单的常见问题解答系统。我希望您喜欢本教程,并且可以在下一个项目中使用它。如果您喜欢这篇文章,请不要忘记分享它!

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

以上是使用自定义帖子类型通过 WordPress 创建自定义常见问题解答系统的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP的当前状态:查看网络开发趋势PHP的当前状态:查看网络开发趋势Apr 13, 2025 am 12:20 AM

PHP在现代Web开发中仍然重要,尤其在内容管理和电子商务平台。1)PHP拥有丰富的生态系统和强大框架支持,如Laravel和Symfony。2)性能优化可通过OPcache和Nginx实现。3)PHP8.0引入JIT编译器,提升性能。4)云原生应用通过Docker和Kubernetes部署,提高灵活性和可扩展性。

PHP与其他语言:比较PHP与其他语言:比较Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能PHP与Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

PHP:网络开发的关键语言PHP:网络开发的关键语言Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP:许多网站的基础PHP:许多网站的基础Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

超越炒作:评估当今PHP的角色超越炒作:评估当今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在现代编程中仍然是一个强大且广泛使用的工具,尤其在web开发领域。1)PHP易用且与数据库集成无缝,是许多开发者的首选。2)它支持动态内容生成和面向对象编程,适合快速创建和维护网站。3)PHP的性能可以通过缓存和优化数据库查询来提升,其广泛的社区和丰富生态系统使其在当今技术栈中仍具重要地位。

PHP中的弱参考是什么?什么时候有用?PHP中的弱参考是什么?什么时候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通过WeakReference类实现的,不会阻止垃圾回收器回收对象。弱引用适用于缓存系统和事件监听器等场景,需注意其不能保证对象存活,且垃圾回收可能延迟。

解释PHP中的__ Invoke Magic方法。解释PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允许对象像函数一样被调用。1.定义\_\_invoke方法使对象可被调用。2.使用$obj(...)语法时,PHP会执行\_\_invoke方法。3.适用于日志记录和计算器等场景,提高代码灵活性和可读性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),