Rewriting a custom-post-type permalink with taxonomy term?

I’m trying to rewrite my url for a custom_post_type named wr_events with one of its custom_taxonomy terms from event_type

add_action('init', 'wr_events');

function wr_events() {

     register_taxonomy(
        'event_type',
        'wr_event',
        array(
            'label' => 'Types',
            'singular_label' => 'Typ',
            'hierarchical' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'events'),
        )
    );

    $labels = array(
        'name' => _x('Events', 'post type general name'),
        'singular_name' => _x('Event', 'post type singular name')
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array('title','editor','thumbnail', 'excerpt'),
        'rewrite' => array(
            //'slug' => 'event',
            'slug' => 'events/%event%',
            'with_front' => false
        ),
        'has_archive' => 'events'
    ); 

    register_post_type( 'wr_event' , $args );
    flush_rewrite_rules();
}

add_action('save_post', 'save_details');

add_filter('post_type_link', 'events_permalink_structure', 10, 4);
function events_permalink_structure($post_link, $post, $leavename, $sample)
{
    if ( false !== strpos( $post_link, '%event%' ) ) {
        $event_type_term = get_the_terms( $post->ID, 'event_type' );
        $post_link = str_replace( '%event%', array_pop( $event_type_term )->slug, $post_link );
    }
    return $post_link;
}

So in my case my taxonomy terms would be “workshops” or “lectures” etc.
url/events/lectures or url/events/workshops lists all my posts related to this “category”, url/events shows a custom archive for all my events. -> this is just what I want however the only thing not working is the complete url to the custom-post itself …

Read More

url/events/lectures/post-name – throws a 404!

Any idea why this is happening? My events_permalink_structure() function seems to work correctly as it replaces my permalinks exaclty the way I want.

I installed the “Rewrite Analyzer” Plugin and it shows me “Regex is empty” for wr_event.

I’ve also tried to flush the Rewrite Rules by visiting the permalink settings. However no effect.

Related posts

Leave a Reply

1 comment