You can see a practical example here: https://wordpress.stackexchange.com/a/142902/19105
Why do you need to use DISTINCT in this situation though? The WP_Query you provided shouldn’t be giving duplicates unless there is a plugin causing trouble.
But I’ll try to answer it anyway. I would suggest keeping the function in functions.php. But move the filter to archive.php around the WP_Query call, like so:
add_filter('posts_distinct', 'search_distinct');
$the_query = new WP_Query( $args );
remove_filter('posts_distinct', 'search_distinct');
If you do this, I also recommend you leave a comment by the search_distinct function. Just explain that the function is used in archive.php — it will help you out in the future if you forget what that function is from.
Also, remove the line: search_distinct(); //Correct?
That is not correct, you typically do not call action/filter functions directly. That is what the “add_filter()” is for.
Complete code:
// functions.php
// Used as a filter for archive.php to eliminate duplicate posts
function search_distinct() {
return "DISTINCT";
}
//archive.php
<?php
$args = array(
'post_type' => 'homily',
'posts_per_page' => -1,
'meta_key' => 'homilist',
'orderby' => 'meta_value',
'order' => 'ASC'
);
// Get posts, make them distinct. search_distinct is defined in functions.php
add_filter('posts_distinct', 'search_distinct');
$the_query = new WP_Query( $args );
remove_filter('posts_distinct', 'search_distinct');
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(); ?>