I want my post-links to look like /%post_id62%_%postname%/ where %post_id62% is the post ID in base62 encoding (e.g. http://example.com/y9Rlf_test/) and my shortlinks to consist of /%post_id62% only (e.g. http://example.com/y9Rlf). This is what i’ve got so far (in my functions.php
) which obviously doesn’t work:
add_action( 'init', 'yoyo_init' );
function yoyo_init() {
add_rewrite_tag( '%post_id62%', '([A-Za-z0-9]+)' );
}
add_action('generate_rewrite_rules','yoyo_generate_rewrite_rules');
function yoyo_generate_rewrite_rules($yoyo_rewrite) {
global $wp_rewrite;
$new_rules['/([0-9A-Za-z]+)/?$'] = 'index.php?p=' .
base622dec($wp_rewrite->preg_index(1)); // DOESNT WORK OF COURSE (executed only once when rewrite_rules are generated)
$wp_rewrite->rules = array_merge($new_rules, $wp_rewrite->rules);
}
add_filter( 'post_link', 'yoyo_post_link', 10, 2 );
function yoyo_post_link( $permalink, $post ) {
if ( false !== strpos( $permalink, '%post_id62%' ) ) {
$post_id62 = dec2base62( $post->ID );
$permalink = str_replace( '%post_id62%', $post_id62, $permalink );
}
return $permalink;
}
add_filter('pre_get_shortlink', 'yoyo_custom_shortlink', 10, 4);
function yoyo_custom_shortlink($false, $post_id, $context, $allow_slugs) {
global $wp_query;
if($post_id or ($context == 'query' and $post_id = $wp_query->get_queried_object_id())) {
return home_url("https://wordpress.stackexchange.com/" . dec2base62($post_id));
}
return false;
}
function dec2base62($number) {
$digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $string = ''; while($number > 0) { $string = $digits[$number % 62] . $string; $number = floor($number / 62); }
return $string;
}
function base622dec($string) {
$digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $number = 0; while(strlen($string) and ($number *= 62 or strlen($string))) { $number += strpos($digits, $string[0]); $string = substr($string, 1); }
return $number;
}
Any idea how to tackle the problem?
Bonus points for avoiding the -N slug suffix when there’s another post with the same title created (which might be avoided actually when setting the link structure to “/%post_id62%_%postname%/” but in order to have the shortlink functionality it should be “/%post_id62%” I guess; cf. Turn off %postname% auto-incrementing?)!
Thanks!