views:

62

answers:

0

Hi,

I have edited my theme in Wordpress to show the 20 most recent comments to each post on the post list. Works fine and all.

However I have nested comments enabled on my WP and would like to show nesting within the 20 recent comments. That is being if a comment is a reply to another comment which is in the recent 20 comments then nest the comments appropirately.

I know this needs to be recursive as potentially the 20 recent comments could each be a reply to each other.

I do not need to worry about the ultiamte parents of each comment, just the parents of the comments which are in the recent 20. So for example if I have a comment which is a reply to a comment which is not in the recent 20, then it is not nested.

So far I managed to get the following code but I know Im getting into a mess:

$idList = array();
$parentList = array();
foreach( $comments as $comment ) { 
    array_push( $idList, $comment->comment_ID );
}

$postStructure = array();
foreach( $comments as $comment ) { 
    if ( in_array( $comment->comment_parent, $idList  ) )  {
     $postStructure[ $comment->comment_parent ][] = $comment->comment_ID;
    } else {
     array_push( $parentList, $comment->comment_ID );
    }
}   

function r( $id, $i = 2 ) {

foreach ( $id as $ide ) {

    if ( in_array( $ide, array_keys($postStructure) ) ) {
     r($postStructure[$ide], $i++);
    } else
    print "CHILD".$i."<br>";
    }
}

foreach ( $postStructure as $parent => $id ) {
    if ( in_array( $parent, $parentList ) ) {
    print "PARENT " . $parent . " " . $id . "<br>";
    foreach ( $id as $i ) {
    if ( in_array( $i, array_keys($postStructure) ) ) {     
    r($postStructure[$i]);     
    } else
    print "CHILD " . $i . "<br>";
    }
    }


}

I know the variable names couldve been better.

Any pointers would be much appreciated, thanks.