0

Questions says it pretty much ... Is it possible to change the comment meta for all comments of a specific post?

I know it probably works like this:

$comments = get_comments( array(

    'post_id' => $post->ID,

) );

foreach( $comments as $comment ) {

    update_comment_meta( $comment->comment_ID, 'accepted', '0' );

}

But is there a more elegant approach?

  • what does it mean "elegant"? – Mark Kaplun May 3 '17 at 18:49
  • I could imagine this solution is not very performant with many comments? – GDY May 3 '17 at 18:53
  • @Grandy can you explain more about what specifically you are trying to do, where you are trying to accomplish it, and what you have tried so far? – Stephen S. May 3 '17 at 19:05
  • sure, so there is a question of why does it matter. If you going to run it once a year, performances will not matter much and maintenability might be much more important – Mark Kaplun May 3 '17 at 19:09
1

Your approach will be very slow if there are N no of comments. Use following approach for much faster execution.

global $wpdb;
$sql = '
    SELECT GROUP_CONCAT( comment_ID ) AS ids
    FROM  `wp_comments` 
    WHERE comment_post_ID =  '.$POST_ID;

    $ids = $wpdb->get_results($sql, ARRAY_A);

if(isset($ids[0]['ids']) && $ids[0]['ids'] != ''){
    $wpdb->query('
        UPDATE wp_commentmeta 
        SET meta_value = 0 
        WHERE comment_id IN ('.$ids[0]['ids'].') 
        AND meta_key = "accepted"
    ');
}

P.S : Haven't tested the code.

  • Worked fine, thank you. Consider using $wpdb->comments and $wpdb->commentmeta just if anyone want to copy this ;) I didn't tested the actuall speed benefit against my solution but im pretty sure this is faster (because SQL pretty directly). – GDY May 4 '17 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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