目录
自定义帖子类型和分类
第 1 步:创建自定义帖子类型
第 2 步:创建自定义分类
第 3 步:创建 [faq] 简码
第 4 步:总结代码
改进空间
结论
首页 后端开发 php教程 使用自定义帖子类型通过 WordPress 创建自定义常见问题解答系统

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

Aug 30, 2023 pm 10:33 PM

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

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

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

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热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.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

11个最佳PHP URL缩短脚本(免费和高级) 11个最佳PHP URL缩短脚本(免费和高级) Mar 03, 2025 am 10:49 AM

长URL(通常用关键字和跟踪参数都混乱)可以阻止访问者。 URL缩短脚本提供了解决方案,创建了简洁的链接,非常适合社交媒体和其他平台。 这些脚本对于单个网站很有价值

Instagram API简介 Instagram API简介 Mar 02, 2025 am 09:32 AM

在Facebook在2012年通过Facebook备受瞩目的收购之后,Instagram采用了两套API供第三方使用。这些是Instagram Graph API和Instagram Basic Display API。作为开发人员建立一个需要信息的应用程序

在Laravel中使用Flash会话数据 在Laravel中使用Flash会话数据 Mar 12, 2025 pm 05:08 PM

Laravel使用其直观的闪存方法简化了处理临时会话数据。这非常适合在您的应用程序中显示简短的消息,警报或通知。 默认情况下,数据仅针对后续请求: $请求 -

构建具有Laravel后端的React应用程序:第2部分,React 构建具有Laravel后端的React应用程序:第2部分,React Mar 04, 2025 am 09:33 AM

这是有关用Laravel后端构建React应用程序的系列的第二个也是最后一部分。在该系列的第一部分中,我们使用Laravel为基本的产品上市应用程序创建了一个RESTFUL API。在本教程中,我们将成为开发人员

简化的HTTP响应在Laravel测试中模拟了 简化的HTTP响应在Laravel测试中模拟了 Mar 12, 2025 pm 05:09 PM

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显着减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

php中的卷曲:如何在REST API中使用PHP卷曲扩展 php中的卷曲:如何在REST API中使用PHP卷曲扩展 Mar 14, 2025 am 11:42 AM

PHP客户端URL(curl)扩展是开发人员的强大工具,可以与远程服务器和REST API无缝交互。通过利用Libcurl(备受尊敬的多协议文件传输库),PHP curl促进了有效的执行

在Codecanyon上的12个最佳PHP聊天脚本 在Codecanyon上的12个最佳PHP聊天脚本 Mar 13, 2025 pm 12:08 PM

您是否想为客户最紧迫的问题提供实时的即时解决方案? 实时聊天使您可以与客户进行实时对话,并立即解决他们的问题。它允许您为您的自定义提供更快的服务

宣布 2025 年 PHP 形势调查 宣布 2025 年 PHP 形势调查 Mar 03, 2025 pm 04:20 PM

2025年的PHP景观调查调查了当前的PHP发展趋势。 它探讨了框架用法,部署方法和挑战,旨在为开发人员和企业提供见解。 该调查预计现代PHP Versio的增长

See all articles