Creating an FAQ Accordion in single page without Custom Fields Plugins
Instead of using custom fields, we’ll leverage the WordPress content editor to input FAQ data directly into the post content. This method provides flexibility and avoids the need for additional plugins.
-
Identify the FAQ Content Structure:
- Decide on a clear format for inputting FAQs into the post content. For instance:
- Decide on a clear format for inputting FAQs into the post content. For instance:
-
Create a Custom Function:
- Develop a PHP function to parse the post content and extract FAQ data based on the defined structure.
-
Integrate into single.php:
- Include the custom function in your
single.php
template. - Call the function to retrieve FAQ data and display it in an accordion format.
- Include the custom function in your
Display Post Content and FAQs In your single.php
, add the following code to display the FAQs within the post content area:
Add JavaScript for Accordion Create the faq-accordion.js
file in your theme’s js
directory with the following content:
<script>
document.addEventListener(‘DOMContentLoaded’, function() {
var faqItems = document.querySelectorAll(‘.faq-item’);
faqItems.forEach(function(item, index) {
var question = item.querySelector(‘.faq-question’);
var answer = item.querySelector(‘.faq-answer’);
if (index === 0) {
question.setAttribute(‘aria-expanded’, ‘true’);
answer.style.display = ‘block’;
}
question.addEventListener(‘click’, function() {
var expanded = question.getAttribute(‘aria-expanded’) === ‘true’;
faqItems.forEach(function(otherItem) {
var otherQuestion = otherItem.querySelector(‘.faq-question’);
var otherAnswer = otherItem.querySelector(‘.faq-answer’);
otherQuestion.setAttribute(‘aria-expanded’, ‘false’);
otherAnswer.style.display = ‘none’;
});
if (!expanded) {
question.setAttribute(‘aria-expanded’, ‘true’);
answer.style.display = ‘block’;
}
});
});
});
</script>
Add CSS for StylingCreate the faq-accordion.css
file in your theme’s css
directory with the following content:
Step 5: Add FAQs in Post Content
- Go to your WordPress admin dashboard.
- Navigate to Posts > Add New (or edit an existing post).
- Title the post as desired.
- n the content area of the post, add your FAQs in the format
Question|Answer
separated by new lines. For example: - Publish the post.
Now, when you view a single post, the FAQ accordion should be displayed with the questions and answers provided in the content area of the post. The JavaScript and CSS files will provide the necessary functionality and styling.