I have a problem that I can't solve. Thanks to anyone who can help me.
My goal is to remove the custom post type name from the URL and insert the associated taxonomy term name in its place. Also, the taxonomy name must not appear in the URL.
first -> mysite/custom-post-type/tax-term/single-custom-post-type
correct -> mysite/tax-term/single-custom-post-type
I was able to do this without too much trouble and the taxonomy term store works too. The problem is that the site's pages and posts are now returning a 404 error.
If I set the permalink structure to plain everything works, but this is not SEO friendly.
here is my code.
/*=========================================================================
CUSTOM POST TYPE
=========================================================================*/
function register_structures_post_type()
{
$labels = array(
'name' => _x('Structures', 'Post type general name', 'twentytwentyfour'),
'singular_name' => _x('Structure', 'Post type singular name', 'twentytwentyfour'),
// Other labels...
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => '%type%', 'with_front' => false),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 10,
'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
);
register_post_type('structures', $args);
}
add_action('init', 'register_structures_post_type');
/*=========================================================================
TAXONOMY
=========================================================================*/
function register_type_taxonomy()
{
$labels = array(
'name' => _x('Type', 'taxonomy general name', 'twentytwentyfour'),
'singular_name' => _x('Type', 'taxonomy singular name', 'twentytwentyfour'),
// Other labels..
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'structures', 'with_front' => false),
);
register_taxonomy('type', array('strutture'), $args);
}
add_action('init', 'register_type_taxonomy');
/*=========================================================================
FILTER LINK
=========================================================================*/
function custom_post_type_permalink_structures($post_link, $post, $leavename, $sample)
{
if ('structures' == $post->post_type) {
$terms = wp_get_object_terms($post->ID, 'type');
if (!empty($terms) && !is_wp_error($terms)) {
return str_replace('%type%', $terms[0]->slug, $post_link);
}
}
return $post_link;
}
add_filter('post_type_link', 'custom_post_type_permalink_structures', 10, 4);