Fergal Andrews
Fergal Andrews

Reputation: 314

Wordpress Custom Permalink Structure for Custom Post Type

I have spent a number of hours trying to find a solution to this problem, read many articles and tried many 'fixes' from both stackoverflow and elsewhere, all without success.

I am trying to create a permalink structure for a a custom post type I have created in Wordpress (version 4.5.3). The post type is called 'videos'. By default my permalinks look like 'http://localhost.wordpress/videos/my-video-post'. I would like to replace 'videos' in the link with the category name for the post, i.e. 'http://localhost.wordpress/computer-lessons/my-video-post', where the category is 'computer-lessons'. I have been able to create working permalinks such as 'http://localhost.wordpress/categories/computer-lessons/my-video-post' using the code below but I want to get rid of the '/categories/' part in the link. The code I am currently using is

add_action( 'init', 'video_post_type' );

function video_post_type() {
    register_post_type( 'video', array(
        'labels' => array(
            'name' => 'Videos',
            'singular_name' => 'Video',
        ),
        'rewrite' => array('slug' => 'categories/%category%'),
        'taxonomies'  => array('post_tag', 'category'),
        'description' => 'Video resources.',
        'public' => true,
        'menu_position' => 20,
        'supports' => array( 'title', 'editor', 'custom-fields' )
      ));
  }

function videos_post_link( $post_link, $id = 0 ){
    $post = get_post($id);  
    if ( is_object( $post ) ){
        $terms = wp_get_object_terms( $post->ID, 'category' );
        if( $terms ){
            return str_replace( '%category%' , $terms[0]->slug ,   $post_link );
        }
    }
    return $post_link;  
}
add_filter( 'post_type_link', 'videos_post_link', 1, 3 );

I have tried many, many variations of this code but whenever I get the structure I am looking for the permalink gives a 404.

I am starting to think this may not be possible because I have read so many articles and posts related to this and have not found a working solution.

Many thanks in advance.

Upvotes: 0

Views: 1404

Answers (1)

mattkrupnik
mattkrupnik

Reputation: 537

Just replace your section 'rewrite' => array('slug' => 'categories/%category%') with 'rewrite' => array('slug' => '%category%') just leave %category% and should work.

Important: After all go to permalink options and reset it.

Some more informations you can find here Show only specific categories in permalinks for custom post type in WordPress

Upvotes: 1

Related Questions