I have a custom post type with two custom fields, "year" and "month". There are about 118 posts in total, approximately one per month since 2012.
I would like to display a list of the unique years (2012, 2013, 2014, etc.). Typically, views are used to display posts, but I want to display the unique year values from among all 118 posts. Is that possible? If so, how?
From an architectural perspective, is it *advisable* to use a custom field for this purpose, or would it be wiser to consider a custom taxonomy instead?
Thanks for your response. I haven't decided whether to use the taxonomy or custom field. The interface for the taxonomy—choosing multiple items—is undesirable when only one item should be selected, as in a pull-down menu.
Could you provide the custom code to group the posts by a custom field (year)?
Within your view's loop you should try to add the following:
<wpv-loop>
[heading condition="year" value="[types field='year-field-slug' output='raw'][/types]"]
<h4>[types field='year-field-slug' output='raw'][/types]</h4>
[/heading]
/// add here any other fields you want to display
<li> <h4>[wpv-post-title]</h4> </li>
</wpv-loop>
Where:
- Replace "year-field-slug" with your original year custom field slug.
I ultimately decided to just use the native post date field. This required creating a custom shortcode. The shortcode runs a SQL query to select the unique years and passes each year to a view as an attribute via the render_view() Toolset API function. Here's the SQL query in case it's of interest to others:
$query = "SELECT distinct(SUBSTRING(post_date,1,4)) AS aotm_year FROM {$wpdb->prefix}posts WHERE post_status='publish' AND post_type='aotm' ORDER BY aotm_year DESC";