I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I’ve pasted below, and I do not get duplicated content:
function my_module_init() {
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
function my_content_ctrlr( $content ) {
ob_start();
// This file contains only the following simple text for testing purposes: #########
include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' );
$output = ob_get_contents();
ob_end_clean();
// Add our custom code before the existing content.
return $output . $content;
}
So, I think that we can rule out my original idea that content was being echoed instead of returned.
Another possibility is that there are additional apply_filters()
calls on the_content
somewhere in your site via plugins or the theme. E.g.:
echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );
It’s not uncommon for themes to do that kind of thing, and it would result in my_content_ctrlr()
being called once for each additional occurrence.
You can use some additional checks as illustrated by this snippet to resolve that problem (source).
function pippin_filter_content_sample($content) {
if( is_singular() && is_main_query() ) {
$new_content="<p>This is added to the bottom of all post and page content, as well as custom post types.</p>";
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'pippin_filter_content_sample');