如何在 WordPress 中实现数字 URL?

How to achieve numeric URLs in WordPress?

几天前,我在 WordPress 论坛中遇到了一个关于 WordPress 中数字网址的奇怪问题,即当用户试图将文章/页面的链接设成数字时,WordPress 会添加一个后缀。

假设,如果我有一个像下面这样的 URL

http://example.com/123456789/

WordPress 自动将其改为

http://example.com/123456789-2/

在看到了这个奇怪的问题之后,我就想调试并找出解决方案。 经过几个小时的 WordPress 核心代码调试,我终于找到了解决该问题的方法。以下是我最后想出的解决这个问题的代码。

add_filter( 'wp_unique_post_slug', 'mg_unique_post_slug', 10, 6 );

/**
 * Allow numeric slug
 *
 * @param string $slug The slug returned by wp_unique_post_slug().
 * @param int $post_ID The post ID that the slug belongs to.
 * @param string $post_status The status of post that the slug belongs to.
 * @param string $post_type The post_type of the post.
 * @param int $post_parent Post parent ID.
 * @param string $original_slug The requested slug, may or may not be unique.
 */
function mg_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
 global $wpdb;

// don't change non-numeric values
 if ( ! is_numeric( $original_slug ) || $slug === $original_slug ) {
 return $slug;
 }

// Was there any conflict or was a suffix added due to the preg_match() call in wp_unique_post_slug() ?
 $post_name_check = $wpdb->get_var( $wpdb->prepare(
 "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1",
 $original_slug, $post_type, $post_ID, $post_parent
 ) );

// There really is a conflict due to an existing page so keep the modified slug
 if ( $post_name_check ) {
 return $slug;
 }

// Return our numeric slug
 return $original_slug;
}

如果你有类似的问题,希望本文能帮助你。