SQL Query Modification
SQL Query Modification
To ensure privacy at the database level, this plugin hooks into the WordPress comment retrieval process. Instead of filtering results after they are fetched from the database, it modifies the underlying SQL query to ensure that unauthorized comments are never returned in the result set.
The comments_clauses Filter
The plugin utilizes the comments_clauses filter, which intercepts the parts of the SQL query (JOIN, WHERE, GROUP BY, ORDER BY, etc.) before it is executed by WP_Comment_Query.
By modifying the where clause, the plugin injects conditional logic that checks the relationship between the current user and the comment.
Permission Logic
The SQL modification applies different visibility rules based on the current user's role and identity:
- Administrators: If the user has the
manage_optionscapability, the query remains unmodified, allowing them to see all comments. - Post Authors: The query is modified to include comments where the
comment_post_IDbelongs to a post authored by the current user. - Comment Authors: The query is modified to include comments where the
user_idmatches the current logged-in user's ID. - Logged-out Users: The query is modified to return zero results, as there is no
user_idto match.
Impact on Developer Functions
Because the modification happens at the comments_clauses level, it automatically affects standard WordPress template tags and functions. You do not need to update your theme files. The following functions will respect the privacy restrictions:
get_comments()wp_list_comments()WP_Comment_Query
Technical Example
When a non-administrator (User ID: 42) views a post, the plugin appends a condition to the WHERE clause of the SQL query. The resulting query structure looks similar to the following:
SELECT * FROM wp_comments
WHERE (comment_approved = '1')
AND (
user_id = 42 -- The user's own comments
OR comment_post_ID IN ( -- Comments on the user's posts
SELECT ID FROM wp_posts WHERE post_author = 42
)
)
ORDER BY comment_date_gmt DESC
Compatibility and Bypassing
While the plugin handles standard WordPress queries, it is important to note:
- Internal Scope: The filtering logic is handled internally by the
filter_comments_by_privacymethod. While this is an internal implementation detail, it is triggered globally across the site once the plugin is active. - Bypassing Restrictions: If you are a developer and need to fetch all comments regardless of the plugin's restrictions (e.g., for a custom dashboard widget), you can temporarily remove the filter before running your query:
// Remove the privacy filter
remove_filter('comments_clauses', ['WP_Private_Comments', 'filter_comments_by_privacy']);
// Execute your unrestricted query
$all_comments = get_comments();
// Re-add the filter to maintain site privacy
add_filter('comments_clauses', ['WP_Private_Comments', 'filter_comments_by_privacy'], 10, 2);