Created
January 19, 2018 09:35
-
-
Save kierzniak/3f0311a5f2484a66374d08f390c3ddf1 to your computer and use it in GitHub Desktop.
Allow number slug in page url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Allow number slug in page url | |
* | |
* Since WordPress do not allow number links in url we must generate it using | |
* `wp_unique_post_slug` filter. | |
* | |
* @link https://github.com/WordPress/WordPress/blob/4.9.2/wp-includes/post.php#L3798 | |
* | |
* `preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )` | |
* `preg_match( "@^(page)?\d+$@", $slug )` | |
* | |
* @param string $slug The post slug. | |
* @param int $post_ID Post ID. | |
* @param string $post_status The post status. | |
* @param string $post_type Post type. | |
* @param int $post_parent Post parent ID | |
* @param string $original_slug The original post slug. | |
* | |
* @return string | |
*/ | |
function motivast_allow_number_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) { | |
global $wpdb, $wp_rewrite; | |
$number_slug = $original_slug; | |
// If this condition is not true this is not our number slug case | |
if( ! preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $original_slug ) ) { | |
return $slug; | |
} | |
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1"; | |
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $original_slug, $post_type, $post_ID ) ); | |
// If post with this name already exits generate new one with suffix | |
if( $post_name_check ) { | |
$suffix = 2; | |
do { | |
$alt_post_name = _truncate_post_slug( $number_slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; | |
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) ); | |
$suffix++; | |
} while ( $post_name_check ); | |
$number_slug = $alt_post_name; | |
} | |
return $number_slug; | |
} | |
add_filter( 'wp_unique_post_slug', 'motivast_allow_number_post_slug', 10, 6 ); | |
/** | |
* Return empty date rewrites rules to not conflict with our new number format | |
* | |
* Remember to regenerate permalinks structure. | |
* | |
* @param array $date_rewrite The rewrite rules for date archives. | |
* | |
* @return array | |
*/ | |
function motivast_date_rewrite_rules( $date_rewrite ) { | |
return array(); | |
} | |
add_filter( 'date_rewrite_rules', 'motivast_date_rewrite_rules', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment