这个option_{$option_name}
过滤器可用于动态修改选项的值。代替{$option_name}
要修改的选项的名称。
覆盖注释分页选项
分页注释的选项名称为
page_comments
, 因此,我们将创建一个名为
option_page_comments
. 在下面的示例中,我们检查是否正在查看ID数组中的一篇文章以强制分页,如果是,我们将强制对注释分页。否则,将使用“Dashboard”>“Settings”>“Discussion”屏幕中的值。
// 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;
}
覆盖旧帖子的关闭评论选项来回答您的后续问题——是的,我们可以强制为某些旧帖子启用评论,即使讨论屏幕上的设置配置为关闭旧帖子的评论。
// 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;
}