Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Cipta sistem FAQ tersuai dengan WordPress menggunakan jenis siaran tersuai

Cipta sistem FAQ tersuai dengan WordPress menggunakan jenis siaran tersuai

王林
王林asal
2023-08-30 22:33:081192semak imbas

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

Saya baru-baru ini bekerja dengan salah seorang pelanggan saya yang bekerja sebagai perunding profesional dalam bidang kerjanya. Dia bertanya kepada saya sama ada saya boleh melaksanakan sistem Soal Jawab, halaman Soalan Lazim tepatnya. Saya berkata, "Sudah tentu, kami boleh membuat halaman dan menampal soalan dan jawapan dalam gaya yang berbeza" tetapi dia berkata dia akan membuat halaman yang berbeza dan mengkategorikan soalan dan jawapan, dan untuk menjadi lebih teratur dia memerlukan kaedah yang berbeza.

Untuk melakukan ini, saya akan menunjukkan kepada anda cara mengendalikan permintaannya dengan beberapa baris kod ringkas menggunakan jenis siaran tersuai, taksonomi dan kod pendek.

Jenis dan kategori siaran tersuai

Apakah yang diperlukan untuk membina sistem FAQ?

  • Kami memerlukan medan untuk soalan dan jawapan.
  • Kami memerlukan kategori untuk mengklasifikasikan dan membezakan pelbagai jenis soalan dan jawapannya.
  • Dalam kes kami, kami memerlukan kod pendek untuk membenamkan kumpulan soalan ini atau semua soalan ke dalam halaman atau siaran.

Mari mulakan dengan mencipta jenis siaran tersuai.

Langkah 1: Buat jenis siaran tersuai

Sudah tentu, kami akan mulakan dengan menyediakan jenis siaran tersuai untuk projek Soalan Lazim kami. Kami akan mencipta jenis siaran tersuai baharu dengan bantuan fungsi register_post_type(), tetapi jika anda mahukan GUI untuk membuat jenis siaran, anda boleh menggunakan alat penjana jenis siaran GenerateWP. Jana seperti yang saya lakukan dalam contoh ini: 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

<?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' );

?>

Petua: Jika projek anda akan melibatkan lebih banyak jenis siaran tersuai yang mungkin lebih kompleks daripada jenis catatan Soalan Lazim yang ringkas ini, saya boleh mengesyorkan alat hebat yang dipanggil SuperCPT yang Membolehkan anda mencipta jenis siaran baharu dengan kod yang lebih ringkas . Saya juga menulis tutorial tentang SuperCPT, yang boleh anda lihat di sini.

Langkah 2: Buat kategori tersuai

Untuk membezakan antara pelbagai jenis soalan (seperti soalan dan jawapan pelanggan saya tentang keguguran dan kemurungan selepas bersalin), kami memerlukan sistem kategori. Seperti yang anda sedia maklum, WordPress menyediakan fungsi ini melalui taksonomi tersuai.

Fungsi asas di sini ialah register_taxonomy() tetapi sekali lagi, jika anda mahukan antara muka grafik, anda boleh menggunakan alat penjana taksonomi GenerateWP.

Kod adalah seperti berikut:

rrreee

Itu sahaja! Kini anda mempunyai jenis catatan Soalan Lazim dengan taksonomi yang dipanggil "Kategori Soalan Lazim" yang memaut antara satu sama lain! Semak panel pentadbir anda dan anda akan melihat item menu "Kategori Soalan Lazim" di bawah "FAQ". 🎜 🎜Sama seperti kategori siaran biasa, anda boleh menambah, mengedit atau memadamnya dalam halaman Kategori Soalan Lazim, atau menambah kategori baharu semasa menulis item Soalan Lazim baharu. 🎜 🎜Langkah 3: Buat [faq] shortcode🎜 🎜Kini datang bahagian yang menyeronokkan: membina kod pendek. (Jika anda telah membaca catatan saya sebelum ini, anda tahu saya peminat besar kod pendek WordPress.) Kami pada asasnya akan membenamkan item Soalan Lazim ke dalam siaran dan halaman. 🎜 🎜Apa yang berlaku seterusnya:🎜 🎜 🎜Pertanyaan dalam jenis siaran tersuai baharu kami, 🎜 🎜 Tapis kategorinya menggunakan parameter kod pendek, 🎜 🎜Paparkan soalan dan jawapan sebagai tajuk dan kandungan, 🎜 🎜Tunjukkan petikan jawapan melalui pautan "Lagi...", dikawal oleh parameter kod pendek yang lain. 🎜 🎜 🎜Mari mula membina kod pendek. Seperti kod di atas, saya akan menambah beberapa komen yang berguna: 🎜 rrreee 🎜Itu sahaja! Kini kami mempunyai kod pendek yang kemas untuk membenamkan soalan dan jawapan kami. Anda boleh menggunakan nama kelas tuts-faq, tuts-faq-item, tuts-faq-item-title dan tuts- faq -item-content Gayakannya. Walau bagaimanapun, ia sepatutnya baik walaupun anda tidak memasukkan gaya tambahan. 🎜 🎜Langkah 4: Ringkaskan kod🎜 🎜Memandangkan kod ini bukan sahaja melibatkan penggayaan bahagian hadapan tetapi juga memperkenalkan ciri baharu, ia dikira sebagai wilayah pemalam. Itulah sebabnya kita perlu menyimpan kod sebagai pemalam. Apabila kami melakukan ini, kami juga harus memuat semula peraturan penulisan semula mengenai pengaktifan dan penyahaktifan. 🎜 🎜Kod lengkap adalah seperti berikut: 🎜 rrreee 🎜Bilik untuk penambahbaikan🎜 🎜Apabila saya menunjukkan kepada pelanggan saya cara menggunakannya, dia gembira dengan hasilnya. Tetapi di sini kita boleh memanjangkan kod dengan lebih banyak ciri seperti... 🎜
  1. Kesan Akordion: Jika anda ingin menjadikan bahagian Soalan Lazim anda lebih menarik dengan beberapa kesan penukaran, anda boleh menggunakan beberapa pemalam jQuery yang hebat. Jika anda ingin menggunakan UI jQuery, Shane Osbourne mempunyai tutorial hebat tentang cara melakukannya.
  2. Penomboran: Jika anda mempunyai banyak soalan dan jawapan untuk kategori tertentu dan tidak mahu memaparkan semua item sekaligus, anda boleh mengehadkan bilangan siaran dengan menukar parameter posts_per_page bagi pertanyaan dengan kod pendek tersuai dan menggunakan wp_reset_postdata(); Kod di bawah baris menambah kod yang diperlukan untuk pautan penomboran. Ingat untuk mengalih keluar baris 'no_found_rows' => true,, tetapi jika anda tidak mengalih keluarnya, penomboran tidak akan berfungsi! posts_per_page 参数来限制帖子数量自定义短代码的查询,并使用 wp_reset_postdata(); 代码在行下方添加分页链接所需的代码。请记住删除 'no_found_rows' => true, 行,但如果不删除它,分页将无法工作!
  3. 随机问题:假设您想在主页上显示一个随机问题和答案,并且希望它在每次页面刷新时进行更改。您需要做的就是前往自定义查询,将 posts_per_page 参数从 -1 更改为 1 并添加另一行代码 'orderby' => 'random',
Soalan Rawak

: Katakan anda mahu memaparkan soalan dan jawapan rawak pada halaman utama anda, dan anda mahu ia berubah setiap kali halaman dimuat semula. Apa yang anda perlu lakukan ialah pergi ke pertanyaan tersuai anda, tukar parameter posts_per_page daripada -1 kepada 1 dan tambah satu lagi baris kod 'orderby ' => 'rawak', dan anda semua yang terbaik!

Kesimpulan

Beginilah cara anda boleh membina sistem Soalan Lazim yang ringkas dalam WordPress dengan menggunakan jenis siaran tersuai, taksonomi tersuai dan kod pendek. Saya harap anda menikmati tutorial ini dan boleh menggunakannya dalam projek anda yang seterusnya. Jika anda menyukai artikel ini, jangan lupa kongsikannya! 🎜 🎜Adakah anda mempunyai sebarang idea untuk menambah baik sistem FAQ ini? Kongsi komen anda di bawah! 🎜

Atas ialah kandungan terperinci Cipta sistem FAQ tersuai dengan WordPress menggunakan jenis siaran tersuai. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn