I am trying to show Bitly's Post short URLs for my blog posts but something seems off as when I am using this code, I see the output all over the page for menu items etc...

Additionally, the URL doesn't seem to be outputted correctly. After many attempts, I am trying to use this:

function shorturl_after_title( $title ) {
    if ( function_exists('wp_get_shortlink') && is_single() && 'post' == get_post_type() ) {

            $aftertitle = "<br><span class='post-shortlink'>رابط مختصر:
<input type='text' value='<?php echo wp_get_shortlink(get_the_ID()); ?>' onclick='this.focus(); this.select();' />
            $custom_title = $title . $aftertitle;
            return $custom_title;
add_filter( 'the_title', 'shorturl_after_title' );

Can you please help with this? Thanks!


There's a second argument passed to the_title filter, which is the ID of the post the filter is currently operating on. This is important, as you've discovered, because the filter runs any time a title is output- in a menu item, widget, any secondary query, etc., so you need to check if that post ID matches the ID of the post you're currently viewing.

Your other problem is a syntax issue where you set $aftertitle. You've got php open/close braces and an echo inside there where you should be using string concatenation, like the way you join $title . $aftertitle on the next line. Anyway, we can do that a bit differently.

So here's a new version of your function. We can combine the single and post type checks into one, and I think it's safe to assume that wp_get_shortlink exists in this context. We then use php sprintf to generate the string, this is just a personal preference.

function shorturl_after_title( $title, $post_id ) {
    if ( is_singular( 'post' ) && $post_id == get_queried_object_id() ) {
        $text = "%s<br><span class='post-shortlink'>رابط مختصر:<input type='text' value='%s' onclick='this.focus(); this.select();' /></span>";           
        $title = sprintf( $text, $title, wp_get_shortlink( $post_id ) );
    return $title;
add_filter( 'the_title', 'shorturl_after_title', 10, 2 );
| improve this answer | |
  • Thanks! I noticed a few things off and I am wondering if it's just on my end. The short URLs are showing both before the title and after it. It also seems there is a rouge '> being added after the title. Is there perhaps a better way to show something next to the title or below it that doesn't inherent the H and A tags from the title? – Dr.Hariri Jan 1 '19 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.