Related FAQs on Product pages Based on Product Category Taxonomy in Bricks

Updated on 20 Dec 2023

This Pro tutorial provides the steps to modify a Bricks query loop's posts (of a CPT) output to those related to the current post's (another CPT) terms using a Taxonomy type field.

Scenario

CPT: faq
custom field: product_category of type Taxonomy created using ACF
return type: ID

FAQ posts have 1 or more product categories associated with them.

Objective

On single product pages, show all the FAQs associated with the current WooCommerce product's product categories (which again, can be single or multiple).

Solution Approach

  • Create a PHP function that loops through all posts of faq post type, and for each faq, loop through the values of its product_category ACF field of type taxonomy and add the faq to the array of faqs for that product category. This function returns an associative array of faqs with product category ID as the key and corresponding faqs' array as the value.
  • We create another function that gets the current product's product categories, loops over them, checks if the product category ID is in the earlier function's output, and if so, merge its value (array of FAQs) with a new FAQ array in each iteration.
  • Another function that returns the count of the earlier function so the entire Section of "Related FAQs" can be conditionally output only if there's at least 1 related FAQ item.
  • Finally, we set unique faq post IDs of this new FAQ array as the value of post__in query parameter.

Sample Data

Numbers in brackets indicate the post/term ID.

FAQ 1:
 product_category = Automotive (66)

FAQ 2:
 product_category = Automotive (66), Baby (71)

FAQ 3:
 product_category = Watch (64)

View: Single product pages

Any product that has Automotive as its product category should show these FAQs:
 FAQ 1 (393) and FAQ 2 (394)

Any product that has Automotive and Baby as its product categories should show these FAQs:
 FAQ 1 (393) and FAQ 2 (394)

Any product that has Baby as its product category should show this FAQ:
 FAQ 2 (394)

Any product that has Watch as one of its product categories should show this FAQ:
 FAQ 3 (395)

Step 1

Create a faq CPT using ACF.

Register an associated ACF field group tilted say, "FAQ Fields":

Step 2

Create a few FAQ entries and for each, select one or more corresponding product categories.

Step 3

Add the following in child theme's functions.php or a code snippets plugin:

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Instant access to 390+ Bricks code tutorials with BricksLabs Pro