Not sure the following solution is better than the solution in OP, let’s just say is an alternative, probably more hackish, solution.
I think you can use a PHP exception to stop WordPress execution when 'comments_template'
filter is applied.
You can use a custom exception class as a DTO to carry the template.
This is a draft for the excepion:
class CommentsTemplateException extends \Exception {
protected $template;
public static function forTemplate($template) {
$instance = new static();
$instance->template = $template;
return $instance;
}
public function template() {
return $this->template;
}
}
With this exception class available, your function becomes:
function engineCommentsTemplate($myEngine) {
$filter = function($template) {
throw CommentsTemplateException::forTemplate($template);
};
try {
add_filter('comments_template', $filter, PHP_INT_MAX);
// this will throw the excption that makes `catch` block run
comments_template();
} catch(CommentsTemplateException $e) {
return $myEngine->render($e->template());
} finally {
remove_filter('comments_template', $filter, PHP_INT_MAX);
}
}
The finally
block requires PHP 5.5+.
Works the same way, and doesn’t require an empty template.