restricting custom rewrite to just one custom post type

I am using the following code to create a short permalink for one of my custom post types. I have another cpt that I wish to just use the default permalink structure, so what would be the best way to restrict this filtering to just cpt1? to be honest I thought one of the functions here would already handle this (add_permastruct?) but the same permalink rewrite is applied to other cpts. the documentation in the codex is a little thin on this… thanks Rhys

function cpt1_rewrite() {
global $wp_rewrite;
$queryarg = 'post_type=cpt1name&p=';
$wp_rewrite->add_rewrite_tag('%cpt1_id%', '([^/]+)', $queryarg);
$wp_rewrite->add_permastruct('cpt1name', '/cpt1/%cpt1_id%', false);}

function cpt1_permalink($post_link, $id = 0, $leavename) {
global $wp_rewrite;
$post = &get_post($id);
if ( is_wp_error( $post ) )
    return $post;   
$newlink = $wp_rewrite->get_extra_permastruct('cpt1name');
$newlink = str_replace("%cpt1_id%", $post->ID, $newlink);
$newlink = home_url(user_trailingslashit($newlink));
return $newlink;}

add_action('init', 'cpt1_rewrite');
add_filter('post_type_link', 'cpt1_permalink', 1, 3);

Answer

The post_type_link hooks gets called for all links to custom post types, you are responsible for checking the link type. Remember to use the passed $post object (not post ID), otherwise you check the current global $post variable, which may not be the post for which you are creating a link now. So the code you added in your comment is almost correct, I would write it like this:

function cpt1_permalink( $post_link, $post, $leavename )
{
    // Yoda condition to be safe
    // http://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined/2430307#2430307
    if ( 'cpt1name' != $post->post_type ) {
        return $post_link;
    }
    // Rest of your code
}

Attribution
Source : Link , Question Author : rhyslbw , Answer Author : Jan Fabry

Leave a Comment