如何解决wordpress的文章ID不连续问题

习惯设置wordpress固定链接格式为“/%postid%.html”的用户都会碰到链接数字不连续的问题,这是因为wordpress中添加文章、媒体,用户等等各种操作都会占用id,这时有些强迫症用户就会很不爽,想要给文章链接的数字搞连续起来,这时就可以用奇怪的方法完成。

新站的话设置文章格式为“/%postname%.html”

然后把下面的加入主题functions.php中,其实就是自定义文章别名为数字自增。

  1. function auto_generate_numeric_slug($post_id) {
  2. // 检查是否是自动保存,避免无限循环
  3. if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  4. return;
  5. }
  6. // 检查当前用户是否有权限编辑文章
  7. if (!current_user_can('edit_post', $post_id)) {
  8. return;
  9. }
  10. // 检查文章是否已经有别名(slug),避免重复更新
  11. $post = get_post($post_id);
  12. if ($post->post_name) {
  13. return;
  14. }
  15. // 获取文章类型,只为普通文章生成别名
  16. if (get_post_type($post_id) != 'post') {
  17. return;
  18. }
  19. // 获取最后一篇文章的 ID
  20. $args = array(
  21. 'post_type' => 'post',
  22. 'posts_per_page' => 1, // 只获取最后一篇文章
  23. 'post_status' => 'publish', // 只获取已发布的文章
  24. 'orderby' => 'ID',
  25. 'order' => 'DESC',
  26. 'post__not_in' => array($post_id) // 排除当前文章,防止冲突
  27. );
  28. $last_post = get_posts($args);
  29. // 如果存在文章
  30. if ($last_post) {
  31. $last_post_id = $last_post[0]->ID;
  32. $last_slug = get_post_field('post_name', $last_post_id);
  33. // 提取数字部分
  34. if (is_numeric($last_slug)) {
  35. $last_number = (int)$last_slug;
  36. } else {
  37. $last_number = 0;
  38. }
  39. } else {
  40. // 如果没有找到任何文章,起始数字设为 0
  41. $last_number = 0;
  42. }
  43. // 自增数字
  44. $new_number = $last_number + 1;
  45. // 更新当前文章的 slug 为自增的数字
  46. wp_update_post(array(
  47. 'ID' => $post_id,
  48. 'post_name' => $new_number
  49. ));
  50. }
  51. add_action('save_post', 'auto_generate_numeric_slug');
分享发现

使用wp官方提供的图片CDN加速服务修复微博图床

2023-12-14 14:16:46

酷站

一个看P站日榜与按热门搜索P站图的网站-Pixivic.Com

2018-12-23 18:46:54

个人中心
今日签到
私信列表
搜索