The option_{$option_name}
filter can be used to modify the value of an option on the fly. Replace {$option_name}
with the name of the option to be modified.
Override Comment Pagination Option
The option name for paginating comments is page_comments
, so we’ll create a filter called option_page_comments
. In the example below, we check if we’re looking at one of the posts in our array of IDs to force pagination on, and if so, we enforce pagination of comments. Otherwise, the value from the Dashboard > Settings > Discussion screen is used.
// Forces comment pagination for certain posts regardless
// of settings within the Settings > Discussion page.
add_filter( 'option_page_comments', 'wpse_modify_page_comments' );
function wpse_modify_page_comments( $page_comments ) {
if ( is_admin() ) {
return $page_comments;
}
// Array of post IDs where comment pagination is forced on.
$force_comment_pagination = [
149,
150,
151,
];
if ( in_array( get_the_ID(), $force_comment_pagination ) ) {
$page_comments = true;
}
return $page_comments;
}
Override Close Comments for Old Posts Option
To answer your followup question — Yes, we can force comments to be enabled for certain older posts even if the settings on the Discussion screen are configured to close comments on old posts.
// Forces comments for old posts to be *allowed* regardless
// of settings within the Settings > Discussion page.
add_filter( 'option_close_comments_for_old_posts', 'wpse_modify_close_comments_for_old_posts' );
function wpse_modify_close_comments_for_old_posts( $close_comments_for_old_posts ) {
// Don't do anything for the admin area. Return the originally set value of the option.
if ( is_admin() ) {
return $close_comments_for_old_posts;
}
// This array contains the posts IDs where we want to
// override the settings for closing comments for old posts.
// (Comments will be forced open for these posts.)
$close_comments_for_old_posts_overrides = [
149,
150,
151,
];
// Handle case when a comment is being made.
if ( isset( $_POST['comment'] ) && isset( $_POST['comment_post_ID'] ) ) {
if ( in_array( $_POST['comment_post_ID'], $close_comments_for_old_posts_overrides ) ) {
// Comments should be open for this post.
return false;
}
}
// Handle case when post is displayed.
global $wp_query;
if ( ! is_array( $wp_query->posts ) ) {
// There are no posts to display. Don't change the option.
return $close_comments_for_old_posts;
}
foreach ( $wp_query->posts as $post ) {
if ( in_array( $post->ID, $close_comments_for_old_posts_overrides ) ) {
// Comments should be open for this post.
return false;
}
}
// If we get here, return the original value of the option without altering it.
return $close_comments_for_old_posts;
}