// 使用数据库保存文章总数量,并跟随增删文章实时调整
add_action('save_post', function($post_id, $post) {
// 排除修订版和自动保存
if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
return;
}
// 获取变更前的状态
$old_status = $GLOBALS['old_post_status'] ?? '';
$new_status = $post->post_status;
// 调试日志(生产环境可移除)
error_log("Post {$post_id} status change: {$old_status} => {$new_status}");
// 只处理实际状态变更
if ($old_status === $new_status) {
return;
}
//自行配置:保存到数据库某个字段中的文章总数量
$current_count = 0;//将0替换为真实数量
// 发布文章(从非发布状态变为发布状态)
if ('publish' === $new_status && 'publish' !== $old_status) {
//自行配置:这里处理 $current_count + 1
...
}
// 取消发布(从发布状态变为非发布状态)
elseif ('publish' !== $new_status && 'publish' === $old_status) {
//自行配置:这里处理 $current_count - 1
...
}
}, 10, 2);
该代码是一个架构代码,需要你根据自己的需要在自行配置处添加自己的需求配置。
注意:这里仅仅是处理跟随文章新发布、文章状态变化而事实调整你保存的文章总数

