I've scoured the interwebs but can't find a good working example or discussion of the filter posts_distinct
I'm using Advanced Custom Fields but I don't think that could be the problem. Anyway, nothing I try is working.
- Is where I have my function call correct? Or does it go ahead of the WP_Query?
- Do I have to pass any arguments?
//functions.php
function search_distinct() {
return "DISTINCT";
}
add_filter('posts_distinct', 'search_distinct');
//archive.php
<?php
$args = array(
'post_type' => 'homily',
'posts_per_page' => -1,
'meta_key' => 'homilist',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$the_query = new WP_Query( $args );
search_distinct(); //Correct?
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' .the_field('homilist') . '</li>';
}
echo '</ul>';
}
wp_reset_postdata(); ?>
Update: Ended up with a less WordPress-esque solution than I had hoped for, the kind suggestions notwithstanding:
<?php
global $wpdb;
$querystr = "SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = 'homilist'
ORDER BY meta_value ASC";
$homilists = $wpdb->get_results( $querystr, OBJECT);
echo '<select id="homilist">';
for ($i = 1; $i < count($homilists); $i++) {
echo '<option value="'.$homilists[$i]->meta_value.'">'.$homilists[$i]->meta_value.'</option>';
}
echo '</select>';
?>
$homilists
data using set_transient/get_transient. Otherwise any time that code loads it's making a fairly expensive query in your database. You can store that data for a set period of time. And even better, you can clear the transient whenever you update a post so that you don't have to wait for the transient to expire for new posts to appear.