0

i have this code to disable comments after X days based on publish date. How can edit this code to auto close comments based on a specific date using custom field? Thank you.

function close_comments( $posts ) {
    if ( !is_single() ) { return $posts; }
    if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
        $posts[0]->comment_status = 'closed';
        $posts[0]->ping_status    = 'closed';
    }
    return $posts;
}
add_filter( 'the_posts', 'close_comments' );

1 Answer 1

0

Editing your code to use a custom field is fairly trivial...

function close_comments( $posts ) {
  if ( !is_single() ) { 
    return $posts; 
  }
  $cmeta = get_post_meta($posts[0]->ID,'your_field_name',true);
  if ( $posts[0]->post_date_gmt < $cmeta ) {
    $posts[0]->comment_status = 'closed';
    $posts[0]->ping_status    = 'closed';
  }
  return $posts;
}
add_filter( 'the_posts', 'close_comments' );

I am not sure that that approach is the right one though.

  1. You are really just brute forcing a closed status. This is a "display only" hack. It doesn't change the database status at all.
  2. This runs on the front end, every time any post displays and runs for many other queries as well. That strikes me as pretty profligate.

I think I would rethink the whole thing to use wp_cron

2
  • Thank you @s_ha_dum for your answer. If you have a better suggetion (or a plugin) to close comments based on a custom field please share it. I have a custom field with a date and i need to close comments when this date expire. Dec 8, 2013 at 18:07
  • I did share my better idea. Read the last sentence of the answer. That, however, is more code than I feel like writing right now (much less testing). If you want to pursue that get started, post code, and let me know.
    – s_ha_dum
    Dec 8, 2013 at 18:47

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.