Skip to content
Advertisement

Add post_id to post_title only to posts with a post_type of “post “

I need to able to insert the id of the post in the post title. The id should be added to the title everywhere the title appears. It should only be added to posts with post type post and not added to pages, custom post types etc.

I’ve managed to get this far:

function custom1_shortcode_func() {
    global $post;
    ob_start();
    echo get_the_title($post->ID); echo " ("; echo get_the_ID(); echo ")"
    $output = ob_get_clean();
    return $output;
}
add_shortcode('post-id', 'custom1_shortcode_func');

Which returns the post title and the post id, when using [post-id] within a post.

But I need to have post titles modified all over my site, so wherever a post title is shown it is followed by “(post_id)”.

I tried this and it did show the post_id before the post title, but it it changed all titles, including menus:

add_filter('the_title', 'wpshout_filter_example');
function wpshout_filter_example($title) {
    return get_the_ID().$title;
}

Advertisement

Answer

You were close with your second attempt, but as you discovered that works for every title.

What you need to do is fist check the post type is a post and only add the id if it is.

add_filter('the_title', 'add_id_to_title', 10, 2);
function add_id_to_title($title, $post_id) {
    //use the id to check the post type and only add the id if it has a type of "post"
    if(get_post_type($post_id) == "post")
        $title = $post_id.': '.$title;
    return $title;
}

What this does:

  • The the_title filter can take 2 parameters: title (which you were using) and also the id of the post.
  • Using the id, can use the built-in get_post_type function to find out the post type.
  • Then we can and check if the post type is post and if it is we add the id to the title.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement