我正在开发一个Wordpress网站,我使用PHP函数来修改'wp_post'表中的'comment_count'字段。
我不使用自定义帖子类型的评论,所以comment_count字段总是设置为0。
我能够在wp_post字段'post_mime_type'和'menu_order'中写入,但不在'comment_count'字段中。
我试过使用wp_update_post()函数,但它不允许我在'comment_count'字段中写入。我相信这是因为它是WordPress自动计算的字段。
是否有任何方法可以写入comment_count字段而不产生任何不兼容性?
作为参考,Publish Press Revisions插件可以将指定的值写入comment_count字段。
我没有以任何方式测试过这一点,但我认为您可以挂钩到pre_wp_update_comment_count_now
并提供您想要的值,然后只需正常调用wp_update_comment_count_now
。
function my_update_comment_count($postIdToUpdate, int $newStaticCommentCount)
{
// Make sure we only register this once for performance reasons
static $wasRegistered = false;
if(!$wasRegistered){
$wasRegistered = true;
add_filter(
'pre_wp_update_comment_count_now',
static function($ignore, $old, $post_id) use($postIdToUpdate, $newStaticCommentCount) {
if($post_id === $postIdToUpdate) {
return $newStaticCommentCount;
}
return $ignore;
},
10,
3
);
}
wp_update_comment_count_now($postIdToUpdate);
}
my_update_comment_count(1016, 123);
或者,如果正在使用核心get_comments_number()
函数,则有一个同名的钩子:
add_filter(
'get_comments_number',
static function($count, $post_id)
{
if($post_id === 123) {
return 27;
}
return $count;
}
);
我从来没有使用过WordPress之前的评论,所以我不知道计数更新何时被触发,它可能是更好的全局钩子pre_wp_update_comment_count_now
。
add_filter(
'pre_wp_update_comment_count_now',
static function($ignore, $old, $post_id) {
if($post_id === 123) {
return 27;
}
return $ignore;
},
10,
3
);