Advertisement
Creative Coding

Create an FAQ Accordion for WordPress With jQuery UI

by

Creating an FAQ section for your WordPress website is incredibly simple. We're going to use WordPress Custom Post Types for the questions & answers. Then we'll use a jQuery UI accordion to make a nice cross-browser accordion widget. Finally we'll assign a shortcode so that we can put our FAQ on any page or post.

We'll be creating this:


Step 1 Create the Directory and Files

  1. Create a new folder inside your theme folder called faq
  2. Inside the 'faq' folder, create a new file called faq.php
  3. Create another file called faq.js

Step 2 Include the faq.php File

In your functions.php (located in the root directory of your theme) – include the faq.php file you created at the top.

/* functions.php */
include('faq/faq.php');

Step 3 Create the Custom Post Type

  1. To register the Custom Post Type, we are going to hook into the init action. We are using an anonymous function as the second parameter to help keep everything encapsulated in one place. This helps with readability and maintainability.
  2. Set up $labels and $args as seen below.
  3. At the end we call register_post_type('FAQ', $args)
  4. Now if you go into your Admin area you will see a new option in the menu – FAQ (as seen in the image below)
  5. Click Add New Question and enter a few Questions and Answers so that we have something to work with later on. Use the title field for the question, and the main content field for the answer. This allows us to enter any type of content into our answer (such as images & videos) as well as text.
/* Register the Custom Post Type */
/* faq.php */
add_action('init', function() {

	$labels = array(
		'name' => _x('FAQ', 'post type general name'),
		'singular_name' => _x('Question', 'post type singular name'),
		'add_new' => _x('Add New Question', 'Question'),
		'add_new_item' => __('Add New Question'),
		'edit_item' => __('Edit Question'),
		'new_item' => __('New Question'),
		'all_items' => __('All FAQ Questions'),
		'view_item' => __('View Question'),
		'search_items' => __('Search FAQ'),
		'not_found' => __('No FAQ found'),
		'not_found_in_trash' => __('No FAQ found in Trash'),
		'parent_item_colon' => '',
		'menu_name' => 'FAQ'
	);

	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'has_archive' => true,
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title', 'editor', 'page-attributes')
	);
	register_post_type('FAQ', $args);
});

Step 4 Include jQuery, jQuery UI, and faq.js

  1. Load jQuery
  2. Load jQuery UI
  3. Load the stylesheet for the jQuery UI library
  4. Load our custom script faq.js
add_action( 'wp_enqueue_scripts', 'wptuts_enqueue' );
function wptuts_enqueue() {
	wp_register_style('wptuts-jquery-ui-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/south-street/jquery-ui.css');
	wp_enqueue_style('wptuts-jquery-ui-style');

	wp_register_script('wptuts-custom-js', get_template_directory_uri() . '/faq/faq.js', 'jquery-ui-accordion', '', true);
	wp_enqueue_script('wptuts-custom-js');
}

You'll notice we only used one wp_enqueue_script call, because it's important the JavaScript files are loaded in order as they are dependent on each other. Setting jquery-ui-accordion as a dependency makes sure this happens.


Step 5 Setup the Shortcode

Because we want to be able to put our FAQ Accordion on any page/post, we're going to generate a shortcode. Using a shortcode means that we only have to type [faq] inside any post/page in the WordPress Editor to display our FAQ.

add_shortcode('faq', function() {
	return "Shortcode test";
});

Step 6 Get the FAQ Questions & Answers

We can get the data from our custom post type by using the get_posts() function.

  1. numberposts – Here you can limit how many FAQ questions are retrieved
  2. orderby and order – Allows us to change the order of the questions
  3. post_type – This is how we tell WordPress to only fetch our custom post type
add_shortcode('faq', function() {
	$posts = get_posts( array(
		'numberposts' => 10,
		'orderby' => 'menu_order',
		'order' => 'ASC',
		'post_type' => 'faq'
	)); //array of objects returned
});
/* example */
echo $posts[0]->post_content; // will output the answer from the first faq question.

Step 7 Generate the Markup for the jQuery UI Accordion

This is the markup needed for the jQuery UI Accordion :


<div id="wptuts-accordion">
	<h3><a href="">Question Will Go Here</a></h3>
	<div>Answer will be in this div.</div>
</div>

We can generate this by looping over the $posts array.

  1. First we use $faq to store the start of our HTML – we open up a div with an id of wptuts-accordion
  2. Next we start looping through all the posts and adding the result of sprintf to the $faq variable.
  3. sprintf will replace %1$s with the value retrieved from $post->post_title and %2$s with the value returned from $post->post_content
  4. We run $post->post_content through wpautop() to ensure it displays as it was authored in the admin area.
  5. Finally we close off the div and return $faq to output the HTML onto our page.
	$faq  = '<div id="wptuts-accordion">'; // the container, before the loop

	foreach ( $posts as $post ) {
		$faq .= sprintf(('<h3><a href="">%1$s</a></h3><div>%2$s</div>'),
			$post->post_title,
			wpautop($post->post_content)
		);
	}

	$faq .= '</div>'; // finish off by closing the container

	return $faq;

The Full Shortcode

add_shortcode('faq', function() {

	$posts = get_posts(array(  //Get the FAQ Custom Post Type
		'numberposts' => 10,
		'orderby' => 'menu_order',
		'order' => 'ASC',
		'post_type' => 'faq',
	));

	$faq  = '<div id="wptuts-accordion">'; //Open the container
	foreach ( $posts as $post ) { // Generate the markup for each Question
		$faq .= sprintf(('<h3><a href="">%1$s</a></h3><div>%2$s</div>'),
			$post->post_title,
			wpautop($post->post_content)
		);
	}
	$faq .= '</div>'; //Close the container

	return $faq; //Return the HTML.
});

Final Step

Phew! If you have got this far, well done – you're nearly there! At the moment we've managed to output all the data needed for our accordion, all that's left to do is place this in faq.js:

(function(){
	jQuery("#wptuts-accordion").accordion();
})();
Related Posts
  • Code
    Plugins
    Create a Shortcode to List Posts With Multiple ParametersPost listing shortcode main image400
    On many of the client sites I build, I find there are times when I need to include a post listing on a page. I'm not talking about archive pages here, but adding a custom listing to an existing static page. For example, I might want to list some posts on the 'About' page, or the site may require an in-depth page for a topic, with a list of posts and custom post types related to that topic. One way to do this is by creating a custom page template to include the current page content plus the results of a second custom query, but if you want more flexibility over how you list posts, or just want to do it a few times, a shortcode will be a simpler solution. In this tutorial, I'll show you how to create a simple shortcode to list all posts of a custom post type, and then I'll expand on that to create a shortcode with various parameters that users can specify to list posts however they want.Read More…
  • Code
    Plugins
    Integrating Multiple Choice Quizzes in WordPress – Creating the FrontendIntegrating multiple choice quizzes in wordpress
    This is the second part of the series on developing a multiple choice quiz plugin for WordPress. In the first part we created the backend of our plugin to capture the necessary data to store in the database. In this final part, we will be creating the frontend of the plugin where the users can take quizzes and evaluate their knowledge.Read More…
  • Code
    Plugins
    Integrating Multiple Choice Quizzes in WordPress - Creating the BackendIntegrating multiple choice quizzes in wordpress
    Multiple choice questions are something that most of us have faced at least once in our life. We love them because we can provide correct answers by logically thinking about provided possibilities, even if we don't exactly know the correct answer. Also answering takes less time which makes it so popular. Creating a multiple choice quiz in WordPress can be a very exciting and profitable task. You can use it in your personal blog to attract more visitors, or you can create a premium section with advanced quizzes, or you can create quizzes focusing on popular certification exams. There are numerous possibilities for making it profitable.Read More…
  • Code
    Business
    Making the Best of Google AdSense in WordPressGoogleadsensepreview
    Blog monetization is not a "must", but it's a very important source of motivation. Whether you're blogging alone or along with some authors you gathered, earning even a few bucks a month can change your and/or your authors' approach to your blog. Since Google AdSense is one of the easiest and most popular ways for blog monetization, we're going to see how to use it with a WordPress blog with multiple authors. (Although, this tutorial will also work for single bloggers.) We'll be covering how to set up profile fields for authors' AdSense ads and how to display those ads with a function, with a widget, with a shortcode and automatically inside posts.Read More…
  • Code
    Creative Coding
    Improving Your Work-Flow - Separate Your Mark-Up From Your Logic!Vr
    In this tutorial I'm going to explain a technique that allows you to utilize a template file for all of your HTML needs! No longer will you need to 'echo' strings from inside your functions, or worry about dropping in and out of PHP just to output some mark-up. I've spent many years utilising MVC frameworks (such as Zend and nowadays Laravel) where it's a best practice to separate your 'programming logic' (functions or methods) from your 'view' (the resulting HTML mark-up). This always leads to a more maintainable code-base and it's actually a lot easier to write. Having this background prompted me to come up with a similar solution when developing plugins for WordPress! It's nothing too fancy - it's just a little 'helper' that will allow you to remove all the HTML snippets and awkward 'escaping' from your functions and place them safely away in their own 'template' file. So, I hope this tutorial sounds interesting to you and without further ado, let's begin!Read More…
  • Code
    Theme Development
    Adding a Responsive jQuery Slider to Your WordPress ThemeSlider ft image
    Today I'm going to take you through integrating a responsive jQuery slider into your WordPress theme or site. It's not a groundbreaking tutorial but it's one that's rarely done right, so I'd like to try and fix that. In this tutorial we're going to cover every step from creating a custom post type to hold our slides, to actually using the slider within our site. We're going to be using the lovely FlexSlider 2 by WooThemes as it's a very well-coded responsive slider that's licensed under the GPLv2 License. If you're interested, you can take a look at the code for FlexSlider in its GitHub Repository.Read More…