In a project that I am currently working on, there's a custom field group created in Advanced Custom Fields called "Trend report meta" and it has 'Report PDF' and 'Report Category' custom fields. This group is set to appear in a Custom Post Type named 'Trend Report'.
'Report Category' is a Select field with these pre-set values:
1: 1H 2014
2: 2H 2014
3: 1H 2015
4: 2H 2015
5: 1H 2016
6: 2H 2016
The requirement is to display the trend reports organized by the various categories like this:
In this article I share the code for showing the above on a Page. The idea is to obtain all the unique values of a custom field (meta key) across all entries of a specific CPT and then loop through the array of the custom field's values.
But first, screenshots of the backend:
Custom field group overview:
Report PDF and Report Category fields, expanded:
Sample Trend Report CPT entry:
First I placed a function that returns an array of unique values of a meta key from all Posts of a supplied CPT in child theme's functions.php:
To view the full content, please sign up for the membership.
Already a member? Log in below or here.
So, the code is first looking for all unique values of the key ‘report_category’ ( which is basically 6 select options that you gave ) and pushing it into an array.
Then you are using a foreach loop for each unique value, lets say ‘1H’ and all the posts that has ‘1H’ in ‘report_category’ will be fetched and shown and then the loop will continue with other value of the key ‘report_category’.
So, with this you’ll get posts aligned with respect to ‘report_category”s unique values.
Is this right?
No. It is only looking for unique values of that meta key amongst the published Posts of that CPT. Meaning, even though there are 6 select options only 3 groups of div.report-category appear on the front-end because the published entries of the CPT have one of those 3 report categories.
Right.
Thanks. Impressive (complex) work! 🙂
Your code example for the functions.php file says
$type = 'post'
. Shouldn’t that be$type = 'trend_reports'
? Or am I just not familiar enough with direct DB queries?