ben blogs

wherever you go, there you are

Marginally Better Shortlinks

I’ve found myself tinkering with WordPress stuff a lot lately. Here’s another quick change I made for nicer shortlinks with a shorter domain that I have.

This was inspired by trawling through jwz’ archives and hacks. This post in particular.

The first piece of this puzzle is adding this location block to the nginx configs for bhh.sh. There’s probably a better way to do this to handle more types or remove the extra redirect.

location ~* /p/(.*) {
  return 302 https://benharri.org?p=$1;
}

The other half is filtering the shortlink on the WordPress end. I’ve added this to the functions.php of my theme. Basic logic here is based on jwz’ base64 shortlinks, just minus the base64 and dumping the post ID right in there.

add_filter( 'pre_get_shortlink', 'bhhsh_shortlink', 10, 4 );

function bhhsh_shortlink( $shortlink, $id, $context, $allow_slugs ) {
  if ($context == 'query' && !is_singular())
    return false;

  $post = get_post( $id );
  if ( empty( $post ) )
    return false;
  $id = $post->ID;
  if ( empty( $id ) )
    return false;

  return 'https://bhh.sh/p/' . $id;
}

Also on: tilde.zone bsky.app benharri.micro.blog

Likes, Bookmarks, and Reposts

  • ^K

One response

  1. ~ben

    it was benharri.org/?p=2291 which is uglier and uses the long domain

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, make a post that contains the link to this post and enter the URL of your response. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Learn More)