I know this questions has been asked a lot, but after working on it for 6 hours straight I can not find a good solutions anywhere.
My site has a Custom Post Type and taxonomy. My taxonomy are for example HP, Dell and Asus. Every product has checked there taxonomy. Now I need to rewrite my url to give me a different link (ie products/$taxonomy/$productname
), so the outcome should be products/asus/n56jn
. Asus is the taxonomy, n56jn is the product name.
Functions.php
Register Post Type
function site_add_cpt() {
register_post_type( 'cpt_products', array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' ),
'all_items' => __( 'View Products' ),
'add_new' => __( 'New Product' ),
'add_new_item' => __( 'New Product' ),
'edit_item' => __( 'Edit Product' ),
'view_item' => __( 'View Product' ),
'search_items' => __( 'Search Products' ),
'no_found' => __( 'No Products Found' ),
'not_found_in_trash' => __( 'No Products in Trash' )
),
'public' => true,
'publicly_queryable'=> true,
'show_ui' => true,
'show_in_nav_menus' => true,
'capability_type' => 'page',
'hierarchical' => true,
'rewrite' => array( 'slug' => '%product_item%', 'with_front' => false ),
'menu_icon' => 'dashicons-cart',
'menu_position' => 21,
'supports' => array( 'title', 'editor', 'page-attributes', 'revisions' ),
) );
);
}
add_action('init', 'site_add_cpt');
Register Taxonomy
function site_add_tax() {
register_taxonomy(
'tax_products',
'cpt_products',
array(
'labels' => array(
'name' => __( 'Product Categories' ),
'singular_name' => __( 'Product Category' ),
'search_items' => __( 'Search Product Categories' ),
'all_items' => __( 'All Product Categories' ),
'parent_item' => __( 'Parent Product Category' ),
'parent_item_colon' => __( 'Parent Product Category:' ),
'edit_item' => __( 'Edit Product Category' ),
'update_item' => __( 'Update Product Category' ),
'add_new_item' => __( 'Add New Product Category' ),
'new_item_name' => __( 'New Product Category' ),
'menu_name' => __( 'Product Categories' )
),
'public' => true,
'hierarchical' => true,
'show_in_nav_menus' => true,
'show_admin_column' => true,
'rewrite' => array( 'slug' => 'products', 'with_front' => false, 'hierarchical' => true )
));
}
add_action('init', 'site_add_taxt');