WordPress: Adding “Get Shortlink” to Custom Post Types

For some reason, by default, WordPress only includes the “Get Shortlink” button when editing posts; not when editing any kind of custom post type or when editing pages. Honestly, I’m not sure why, since pages and custom post types all use the same basic short URL as standard posts (example.com/?p=[post_id]).

The solution is simple, though. You just need to hook into the get_shortlink filter. Following is a simple function that will help you add the button to all “publicly_queryable” post types in your theme.

if( !function_exists( 'my_theme_cpt_shortlinks' ) ) {
  /**
  * Allow shortlinks to be retrieved for pages and custom post types
  */
	function my_theme_cpt_shortlinks( $shortlink, $id, $context, $allow_slugs=true ) {
		/**
		 * If query is the context, we probably shouldn't do anything
		 */
		if( 'query' == $context )
			return $shortlink;

		$post = get_post( $id );
		$post_id = $post->ID;

		/**
		 * If this is a standard post, return the shortlink that was already built
		 */
		if( 'post' == $post->post_type )
			return $shortlink;

		/**
		 * Retrieve the array of publicly_queryable, non-built-in post types
		 */
		$post_types = get_post_types( array( '_builtin' => false, 'publicly_queryable' => true ) );
		if( in_array( $post->post_type, $post_types ) || 'page' == $post->post_type )
			$shortlink = home_url('?p=' . $post->ID);

		return $shortlink;
	}
}
add_filter( 'get_shortlink', 'edui2011_cpt_shortlinks', 10, 4 );

3 Responses

  • Thank you! My website uses a lot of custom post types so this solution comes perfect for me :)

  • Todd Nagel

    Yes, thanks from me as well..I have been working on my clients site for 2 years, and our old editor plugin finally had to go, and just for a spell checker, Jet Pack was installed..

    then clients calls me and says the short links changed, apparently the old plugin was making shortlinks before wordpress started doing it, after changing the Jet Pack settings they went back to ?p=, they went back to ?p= after I deactivated the plugin apparently before installing Jet Pack..

    looked long and hard for this one, I didn’t seem to see much about the ‘get_shortlink’ filter, and yours is nicely done, I was able to make it do what I needed..we only wanted the actual post_name to appear..(long story)..

    Todd

    • Glad it helped!