如何在帖子和页面中使用数字URL

时间:2017-04-05 作者:jeremyers

在我当前所有的Wordpress安装中,每当我们尝试创建一个只有数字的帖子URL时,它会在末尾添加“-2”,如下所示:

实例com/002/

成为

实例com/002-2/

起初我认为这是由于Wordpress的默认行为,即防止重复URL,但当我输入很长的随机数字字符串时,我得到了相同的行为…

实例电话:9020983498207850789287349082078930/

成为

实例电话:9020983498207850789287349082078930-2/

之前已经讨论过这个问题,但是

Can I use a number for a post/page slug?

Why can posts never have a number as the link?

最后一个链接有一些建议的代码来修复它,但强烈建议不要使用它。。。。

1 个回复
最合适的回答,由SO网友:MagniGeeks Technologies 整理而成

希望下面的代码可能会有所帮助

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;
}
代码取自http://magnigenie.com/how-to-achieve-numeric-urls-in-wordpress/

相关推荐

Two urls for one website

我有一位客户,他用一个名为“firstname lastname.ch”的url开始了他的小生意。因为他很幸运能够成长,现在需要一个合适的URL,所以他希望自己的网站有另一个URL,名为“businessype lastname.ch”在没有太多管理和SEO问题的情况下,实现这一目标的最佳方式是什么。谢谢