1

I know this question as been asked several times, but this question is not exactly the same. I have two functions to change the url of single custom post type, but couldn't figure out how make this work for multiple CPTs. What I have tried:

  1. Simply copy the functions and rename them - won't work, they overwriting each other
  2. Tried to add lines within the function twice - fatal error
  3. And tried to make this $queryarg = 'post_type=article&p='; to an array - but add_rewrite_tag only accepts one single string

So that's the code:

    function custom_post_rewrite() {

        global $wp_rewrite;
        $queryarg = 'post_type=article&p=';
        $wp_rewrite->add_rewrite_tag( '%cpt_id%'    , '([^/]+)', $queryarg );
        $wp_rewrite->add_rewrite_tag( '%cpt_type%'  , '([^/]+)', $queryarg );
        $wp_rewrite->add_rewrite_tag( '%cpt_title%' , '([^/]+)', $queryarg ); 
        $wp_rewrite->add_permastruct( 'article'     , '/%cpt_type%/%cpt_title%-id=%cpt_id%', false );


    }
    add_action( 'init', 'custom_post_rewrite' );


    function custom_post_permalink( $post_link, $id = 0, $leavename ) {

        global $wp_rewrite;
        $post       = get_post( $id );
        $uni_id     = get_post_meta( $post->ID, 'unique_post_identifier', true);
        $post_type  = get_post_type( $post->ID );
        $post_title = sanitize_title( get_the_title( $post->ID ));

        if ( is_wp_error( $post ) )
            return $post;
            $newlink = $wp_rewrite->get_extra_permastruct( 'article' );
            $newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
            $newlink = str_replace( '%cpt_title%', $post_title, $newlink );
            $newlink = str_replace( '%cpt_type%', $post_type, $newlink );
            $newlink = home_url( user_trailingslashit( $newlink ) );        
        return $newlink;

    }
    add_filter('post_type_link', 'custom_post_permalink', 1, 3);

So that function would produce a permalink like this:

/%cpt_type%/%cpt_title%-id=%cpt_id%

Your Answer

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

Browse other questions tagged or ask your own question.