1

Is there any way how to output wp_list_comments() into a variable?

Something like $output = wp_list_comments(array('reverse_top_level' => false ), $comments);

I am writing a plugin and it would be handy to use standard WordPress function instead of writing my own.

3
  • That's the kind of question one has to ask to the Manual: codex.wordpress.org/Function_Reference/wp_list_comments
    – brasofilo
    Oct 11, 2013 at 11:21
  • 1
    What is it that your Plugin is actually trying to do with the comments? There might be a solution other than using wp_list_comments(). Oct 11, 2013 at 11:43
  • The plugin displays a post with comments as a home page. This is done also via ajax. I want to do progressive loading of comments so it seems to me that I might need to write my own wp_list_comments. I thought I could avoid that.
    – Radek
    Oct 12, 2013 at 0:44

2 Answers 2

2

In the default usage this is impossible due to the nature of the default comment walker which always directly outputs. But the function allows to provide a custom walker.

Further reading about custom walkers: Codex Class reference example custom walker class

You could also use output buffering to save it into a variable (this is considered to be dirty):

ob_start();
wp_list_comments(array('reverse_top_level' => false ), $comments);
$variable = ob_get_clean();
3
  • So walker, that's probably what @brasofilo meant in his comment. Well it is not explained in Codex for wp_list_comments. I'll try and comment here. Thank you especially for the second link :-)
    – Radek
    Oct 11, 2013 at 11:30
  • @Radek If you want a quick solution maybe output buffering is the way to go. It will be hard to do with a custom walker as wp_list_comments() doesn't have a return value in the first place ...
    – s1lv3r
    Oct 11, 2013 at 11:36
  • I was just about to reactivate my answer and suggest output buffering, but you covered that now. +1 Oct 11, 2013 at 11:37
0

According to Function Reference for wp_list_comments, you can set the arg Echo to false to return the list.

I imagine the default walker will not echo the code if this is set to false.

wp_list_comments(array('reverse_top_level' => false, 'echo' => false), $comments);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.