Sort wordpress comment list to get tree view in ES6
The last notes
All English-language materials have been translated fully automatically using the Google service
Wordpress is a great CMS, but I had to struggle to sort the comments in a tree-like order. Thanks to Kobe on stackoverflow for the awesome ES6 sorting feature
We have an array as input
We transform it using the function:
var comments = this.props.data.COMMENTS;
comments = comments.sort ((a, b) => b.comment_parent - a.comment_parent);
const sortComments = (comments) => {
var temp = [... comments];
comments.forEach ((o, index) => {
if (temp [0] .comment_parent === 0) {return;}
var parentIndex = temp.findIndex (o => o.comment_ID === temp [0] .comment_parent);
if (typeof temp [parentIndex]! = "undefined") {
temp [parentIndex] .children? temp [parentIndex] .children.push (temp [0]): temp [parentIndex] .children = [temp [0]];
temp.shift ();
}
});
return temp;
}
And we get the output:
To display comments recursively, you can use example 0xD34F with qna.habr.com
Repost material:
Comments