• Hello, I am looking to filter comments with a hook so that users can only see their own comment. I would like to put this in the child theme folder in functions.php. I have made this alteration in wp-comment-query.php however on updates I do believe those changes should be overwritten. I changed the code from: $where = ‘WHERE = ‘ . $where; to: $where = ‘WHERE user_id = ‘ . get_current_user_id() . ‘ AND comment_approved <> “trash” AND comment_post_ID = ‘ . get_the_id(); and this had been working for the time being but my understanding is that when an update rolls around the code will be obsolete/overwritten.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    That’s right, altering core code is a very poor practice for a number of reasons. Don’t do it. You should use the “pre_get_comments” action hook. The entire WP_Comment_Query object is passed by reference to your callback function. You can then set/unset the various array elements of WP_Comment_Query::query_vars to alter the eventual SQL query. The array keys are the same as the __construct() parameters.

    Thread Starter joshuask8dev

    (@joshuask8dev)

    So I have this for a function to filter out comments by the current user that is logged in ID and per page:

    function wps_get_comment_list_by_user($clauses) {
    
    global $user_ID, $wpdb;
    $clauses['join'] = ", wp_posts";
    
    $where = ‘WHERE user_id = ‘ . get_current_user_id() . ‘ AND comment_approved <> “trash” AND comment_post_ID = ‘ . get_the_id();
    
    return $clauses;
    };
    
    add_filter('pre_get_comments', 'wps_get_comment_list_by_user');

    Are we close to getting it so that comments on each page only show to the user logged in that they posted themselves?

    Moderator bcworkz

    (@bcworkz)

    “pre_get_comments” is an action, not a filter. You should add you callback with add_action(). It basically does the same as add_filter(), but its concept is different. Using the wrong function muddles your code’s (eventual) clarity. With actions there is little point in returning a value. It will be ignored by WP.

    The comments query doesn’t have a SQL clauses filter like WP_Query does for posts, so you cannot use SQL modification to alter the query. Your callback is passed the WP_Comments_Query object by reference, not SQL clauses. You must act upon the object directly. If your function collects the object as $query, do something like
    $query->query_vars['user_id'] = get_current_user_id();

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Using Hooks With Comment Query’ is closed to new replies.