How to get the custom post type permalink in WordPress?

custom post type permalink

Creating a custom post type using custom coding without using any plugin, is a good idea to avoid using access to plugins that cause the website speed issue and sometimes risks. We simply avoid them by doing some custom code for some of the required features. It also happens sometimes that a few default features of WordPress might not be working with custom code. To fix that we again need to do some custom adjustments or create a new solution for those issues. I have also faced an issue like this. I have created a custom post type using the custom code. But getting the Custom post type permalink with these WordPress default functions get_post_type_archive_link, get_post_permalink, and get_permalink is not providing the desired result. So, I have managed to retrieve the permalink link with this custom-made function. I hope, this will also help you get the desired permalink.

Add this function to your function.php file.

if( !function_exists( 'wp_get_post_type_link' )  ){
    function wp_get_post_type_link( &$post_type ){

        global $wp_rewrite; 

        if ( ! $post_type_obj = get_post_type_object( $post_type ) )
            return false;

        if ( get_option( 'permalink_structure' ) && is_array( $post_type_obj->rewrite ) ) {

            $struct = $post_type_obj->rewrite['slug'] ;
            if ( $post_type_obj->rewrite['with_front'] )
                $struct = $wp_rewrite->front . $struct;
                $struct = $wp_rewrite->root . $struct;

            $link = home_url( user_trailingslashit( $struct, 'post_type_archive' ) );       

        } else {
            $link = home_url( '?post_type=' . $post_type );

        return apply_filters( 'the_permalink', $link );

Now use the following code to your required location to get the permalink:

// in my case the custom post type was "wordpress"
<a href="<?php echo esc_url( wp_get_post_type_link( get_post_type() ) ); ?>"><?php echo strtoupper(get_post_type()); ?></a>

I have created the custom post type “wordpress” so, I got my desired permalink result using this function. I have followed the tutorial here.
To get to know more about other JQuery topics, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply