I’m trying to get my taxonomy to show up in my permalink but it keeps leading to 404. If there’s one think I hate about Wordpress, it’s wrestling with the permalink structure and rewrites
The code works fine without the rewrite.
function arttax_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, '%artcat%') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'arttax');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = 'uncategorized';
return str_replace('%artcat%', $taxonomy_slug, $permalink);
}
add_filter('post_link', 'arttax_permalink', 10, 3);
add_filter('post_type_link', 'arttax_permalink', 10, 3);
/** Create Post Type **/
function CPT_init(){
// Articles CPT
register_post_type('articles', array(
'labels' => array(
'name' => __('Articles'),
'singular_name' => __('Article'),
'all_items' => __('View Articles'),
'add_new' => __('New Article'),
'add_new_item' => __('New Article'),
'edit_item' => __('Edit Article'),
'view_item' => __('View Article'),
'search_items' => __('Search Articles'),
'no_found' => __('No Articles Found'),
'not_found_in_trash' => __('No Articles in Trash')
),
'public' => true,
'publicly_queryable'=> true,
'show_ui' => true,
'query_var' => true,
'show_in_nav_menus' => false,
'capability_type' => 'page',
'hierarchical' => false,
'rewrite' => array('slug' => 'articles/%artcat%', 'with_front' => false),
'menu_position' => 5,
'supports' => array('title','editor')
));
}
add_action('init', 'CPT_init');
/** Add Custom Taxonomy **/
function cat_tax_init() {
$labels = array(
'name' => __( 'Article Categories' ),
'singular_name' => __( 'Article Category' ),
'search_items' => __( 'Search Article Categories' ),
'all_items' => __( 'All Article Categories' ),
'parent_item' => __( 'Parent Article Category' ),
'parent_item_colon' => __( 'Parent Article Category:' ),
'edit_item' => __( 'Edit Article Category' ),
'update_item' => __( 'Update Article Category' ),
'add_new_item' => __( 'Add New Article Category' ),
'new_item_name' => __( 'New Article Category' ),
'menu_name' => __( 'Article Categories' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'hierarchical' => true,
'show_in_nav_menus' => true,
'has_archive' => true,
'rewrite' => array('slug' => '/category', 'with_front' => false)
);
register_taxonomy( 'arttax', 'articles', $args );
}
add_action( 'init', 'cat_tax_init');