I’m using the following conditional code to check if any comments on a given post contains a certain string. -The word ‘CHANGES’ in this case. I have it working if I specify the comment_ID directly, but I’d like to have the code use the loop to check all the comments for a given post and apply the appropriate HTML ID.

<?php
    if( have_posts() ) : while (have_posts()) : the_post(); ?>
        <div id="post-<?php the_ID(); ?>" <?php post_class('col-md-6 box');?>>
        <div class="post-box article" 

<!-- custom code begins -->

<?php 

$mystring = get_comment_text($comment_ID = 23);
$findme="CHANGES";
$pos = strpos($mystring, $findme);

if ($pos === false) : ?>
    id="pendingcomment"
<?php else : ?>
    id="notapprovedcomment"
<?php endif; ?>

I’m trying to replace the $mystring reference so that it looks at all of the comments for a post each time the loop cycles. Do I have to run a another loop inside that cycles through the comments everytime? If so, what would that look like?

Thanks in advance for your time!

1 Answer
1

I’ve answered my own question with some more reading and some messing around…

I had to run a ‘foreach’ that cycles through the given post’s comments within the main loop.

The following code looks at all the comments for each post that passes through the loop and checks for a specific string in the comments’ content. Depending on if $findme is matched, a specific HTML ID is written to the div. At a glance, one can see which posts contain specific content in their comments. Party on.

<?php
if( have_posts() ) : while (have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class('col-md-6 box');?>>
<div class="post-box article"  

<?php

$comments = get_comments( array( 'number' => 99, 'post_id' => get_the_ID() ) );

if(get_comments_number()==0) : ?>
        id="pendingcomment"
<?php else : 

    foreach($comments as $comm) :

        $mystring = get_comment_text( $comm );
        $findme="CHANGES!";
        $pos = strpos($mystring, $findme);

        if($pos == true) : ?>
            id="notapprovedcomment"
        <?php elseif($pos == false) : ?>
                id="approvedcomment"
        <?php endif; 

    endforeach;
endif; ?>
>

The code could no doubt be cleaner, but is functional.
Hope someone finds this useful one day.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *