Support » Developing with WordPress » How to add custom taxonomy in custom post type permalink?

  • I have a custom taxonomy called campaign and a custom post type called asset. For assets, I want to have the following permalink structure: mysite.com/<campaign_name>/<asset_name>. I have achieved this by the following code, but now if I go to any normal page with the url structure mysite.com/<pagename> it gives a 404. And when I comment out the rewrite slug part in the function for registering the custom post type, or add this instead ams/%campaign%, it works but that’s not the URL structure I want for my custom post type.

    Code for registering custom taxonomy:

    
    ...
    'rewrite' => array(
    	'slug' => '',
    	'with_front' => true,
    ),
    ...
    

    Code for registering custom post type:

    
    ...
    rewrite' => array(
    	'slug' => '%campaign%',
    	'with_front' => true,
    ),
    ...
    

    Functions for rewrite rules:

    
    function ams_asset_add_rewrite_rules( $rules ) {
    	global $post;
    	if ($post->post_type == 'asset' ) {
    		$new = array();
    		$new['([^/]+)/(.+)/?$'] = 'index.php?asset=$matches[2]';
    		$new['(.+)/?$'] = 'index.php?campaign=$matches[1]';
    		return array_merge( $new, $rules );
    	}
    	return $rules;
    }
    add_filter( 'rewrite_rules_array', 'ams_asset_add_rewrite_rules' );
    
    // Handle the '%campaign%' URL placeholder
    function ams_asset_filter_post_type_link( $link, $post = 0 ) {
    	if ( $post->post_type == 'asset' ) {
    		$cats = wp_get_object_terms( $post->ID, 'campaign' );
    		if ( $cats ) {
    			$link = str_replace( '%campaign%', $cats[0]->slug, $link );
    		}
    	}
    	return $link;
    }
    add_filter( 'post_type_link', 'ams_asset_filter_post_type_link', 10, 2 );
    
    • This topic was modified 3 years, 4 months ago by sadmansh.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Your taxonomy URL really needs a base parameter so your rewrite rule can detect appropriate requests, otherwise it grabs other requests like simple page requests and mishandles them. Just like category URLs by default look like /category/foo/bar, where foo is the category term and bar is the post name. “category” is the base parameter. Your taxonomy needs its own, such as “campaign”, or any other string that represents a unique URL parameter.

    hi @sadmansh

    Please use cpt code and custom taxonomy code in functions.php

    ////////////////////////////////// Create Asset Custom Post Type //////////////////////////////////
    function create_the_asset_posttype() {
    	$labels = array(
    		'name'                => _x( 'Asset', 'Post Type General Name', 'YOUR_TEXT_DOMAIN' ),
    		'singular_name'       => _x( 'Asset', 'Post Type Singular Name', 'YOUR_TEXT_DOMAIN' ),
    		'menu_name'           => esc_html__( 'Asset', 'YOUR_TEXT_DOMAIN' ),
    		'parent_item_colon'   => esc_html__( 'Parent Asset', 'YOUR_TEXT_DOMAIN' ),
    		'all_items'           => esc_html__( 'All Asset', 'YOUR_TEXT_DOMAIN' ),
    		'view_item'           => esc_html__( 'View Asset', 'YOUR_TEXT_DOMAIN' ),
    		'add_new_item'        => esc_html__( 'Add New Asset', 'YOUR_TEXT_DOMAIN' ),
    		'add_new'             => esc_html__( 'Add New', 'YOUR_TEXT_DOMAIN' ),
    		'edit_item'           => esc_html__( 'Edit Asset', 'YOUR_TEXT_DOMAIN' ),
    		'update_item'         => esc_html__( 'Update Asset', 'YOUR_TEXT_DOMAIN' ),
    		'search_items'        => esc_html__( 'Search Asset', 'YOUR_TEXT_DOMAIN' ),
    		'not_found'           => esc_html__( 'Not Found', 'YOUR_TEXT_DOMAIN' ),
    		'not_found_in_trash'  => esc_html__( 'Not found in Trash', 'YOUR_TEXT_DOMAIN' ),
    	);	
    	$args = array(
    		'label'               => esc_html__( 'asset', 'YOUR_TEXT_DOMAIN' ),
    		'description'         => esc_html__( 'Asset', 'YOUR_TEXT_DOMAIN' ),
    		'labels'              => $labels,
    		'supports'            => array( 'title','editor','thumbnail'),
    		'taxonomies'          => array( 'genres' ),
    	
    		'hierarchical'        => false,
    		'public'              => true,
    		'show_ui'             => true,
    		'show_in_menu'        => true,
    		'show_in_nav_menus'   => true,
    		'show_in_admin_bar'   => true,
    		'menu_position'       => 100,
    		'can_export'          => true,
    		'has_archive'         => true,
    		'exclude_from_search' => false,
    		'publicly_queryable'  => true,
    		'query_var' => true,
    		'show_admin_column' => true,
    		'capability_type'     => 'post',
            'rewrite' => array('slug' => 'asset/%campaign%'),
    	);
    	register_post_type( 'asset', $args );
    }
    add_action( 'init', 'create_the_asset_posttype', 0 );
    
    
    ////////////////////////////////// Custom Post Type Texonomies //////////////////////////////////
    function create_the_asset_taxonomy() {  
        register_taxonomy(  
            'campaign',  //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces). 
            'asset',        //post type name
            array(  
                'hierarchical' => true,  
                'label' => 'Categories',  //Display name
                'query_var' => true,
    			'has_archive' => true,
    			'rewrite' => array('slug' => 'asset')
            )  
        );  
    }  
    add_action( 'init', 'create_the_asset_taxonomy');
    

    Asset Post Type Single Link Add Category Slug Function put in functions.php

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

    @anilankola : your code works but… when I try to display the domain.com/asset archive page, it does not work (404). I tried to add a link of this archive in the main menu. When I click on it, I go to domain.com/asset/%campaign% which does not work either.

    When I try to visit domain.com/asset/name-of-the-taxonomy I am redirected to the home page

    Is there any fix to make these things work ?

    Thank you

    @makinero You must set has_archive to “asset” instead of true.

    See here, some example with shows:
    https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to add custom taxonomy in custom post type permalink?’ is closed to new replies.