Want to add custom taxonomy in custom post type permalink? Use the below code to add custom taxonomy in custom post type permalink.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | /** * Register a 'campaign' taxonomy for post type 'asset'. * * @see register_post_type for registering post types. */ function wpdocs_create_campaign_tax_rewrite() { register_taxonomy( 'campaign', 'asset', array( 'rewrite' => array( 'slug' => '', 'with_front' => false, ), ) ); } add_action( 'init', 'wpdocs_create_campaign_tax_rewrite', 0 ); /** * Implements init_hook to register post type. * https://codex.wordpress.org/Function_Reference/register_post_type */ function generic_create_posttype_asset() { register_post_type( 'asset', array( 'labels' => array( 'name' => __( 'Assets' ), 'singular_name' => __( 'Assets' ), 'add_new' => __( 'New Asset' ), 'add_new_item' => __( 'New Asset' ), 'edit_item' => __( 'Edit Asset' ), ), 'description' => 'Campaign ...', 'public' => true, 'hierarchical' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => '%campaign%', 'with_front' => false, ), 'show_in_menu' => true, 'menu_icon' => 'dashicons-category', // https://developer.wordpress.org/resource/dashicons/ . 'supports' => array( 'title', 'editor', 'revisions', 'thumbnail' ), ) ); } add_action( 'init', 'generic_create_posttype_asset' ); /** * Rewrite '%campaign%' with taxonomy assigned. */ function asset_show_permalinks( $post_link, $post ){ if ( is_object( $post ) && $post->post_type == 'asset' ){ $terms = wp_get_object_terms( $post->ID, 'campaign' ); if( $terms ){ return str_replace( '%campaign%' , $terms[0]->slug , $post_link ); } } else { return $post_link; } } add_filter( 'post_type_link', 'asset_show_permalinks', 1, 2 ); function generic_cpt_rewrite_flush() { generic_create_posttype_asset(); flush_rewrite_rules(); } register_activation_hook( __FILE__, 'generic_cpt_rewrite_flush' ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.