I found an answer where the author comments in the code that the post_type_link filter is (only?) for CPTs. How he/she can be sure that his code will run only for CPTs?

From the Wordpress Codex:

post_type_link is a filter applied to the permalink URL for a post OR custom post type prior to being returned by the function get_post_permalink.

The code in discussion:

add_filter( 'post_type_link', 'custom_post_permalink' ); // for cpt post_type_link (rather than post_link)
function custom_post_permalink ( $post_link ) {
    global $post;
    $type = get_post_type( $post->ID );
    return home_url( $type . '/' . $post->post_name . '.html' );
  • If you follow the link on the codex page to the function's source code, you can see exactly where that filter is applied and under what conditions.
    – Milo
    Apr 2, 2017 at 12:57
  • I don't have the necessary knowledge to understand fully that source code, but from my point of view the above code will work both for post and custom post types, or not?
    – Iurie
    Apr 2, 2017 at 13:10

1 Answer 1


Before returning it's result, get_permalink() applies one of 4 filters on the permalink it has generated, depending on the post_type of the post in question:

  1. post_link, when post_type == 'post'
  2. page_link, when post_type == 'page', via get_page_link()
  3. attachment_link, when post_type == 'attachment', via get_attachment_link()
  4. post_type_link, when post_type is not one of the above (i.e., a CPT), via get_post_permalink()
  • I see a little contradiction in the post_type_link description on the WP Codex page. According to the WP Code Reference page, the get_post_permalink retrieves the permalink for a post of a custom post type, so, from my point of view, the post_type_link can't be applied to the permalink URL for a post or custom post type prior to being returned by the function get_post_permalink, because the last can't retrieve the permalink for a post. Probably, this is a typo, and guys from the WP Codex wanted to say "a post of a custom post type" in the post_type_link description?
    – Iurie
    Apr 2, 2017 at 17:25
  • I suppose, you mean the get_post_permalink, not the get_permalink?
    – Iurie
    Apr 2, 2017 at 17:28
  • yes, the description in the codex entry is incorrect and is corrected in the "new" developer's Code Reference entry, post_type_link. Apr 2, 2017 at 17:38
  • 1
    regarding your other comment, no, I meant get_permalink, which has an if/then/else at lines 143-148 that dispatches cases #2-4 in my answer. Apr 2, 2017 at 17:44

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.