Custom post type 404s with rewriting even after resetting permalinks

Step 1, add the rewrite tags for custom event year and month query vars, then register the event post type with those tags in the slug argument of the rewrite argument:

function wpa83531_register_event_post_type(){

    add_rewrite_tag('%event_year%','(\d+)');
    add_rewrite_tag('%event_month%','(.+)');

    register_post_type( 'event',
        array(
            'public' => true,
            'rewrite' => array( 'slug' => 'events/%event_year%/%event_month%' ),
            'has_archive' => false,
            'hierarchical' => false,
            'supports' => array('custom-fields', 'title', 'editor')
        )
    );

}
add_action( 'init', 'wpa83531_register_event_post_type' );

Step 2, filter the post type link to replace those tags with values from custom fields event_year and event_month. If the custom fields don’t exist, some default values are inserted so you can at least preview a post without error:

function wpa83531_event_post_link( $permalink, $post, $leavename ) {
    if ( stripos( $permalink, '%event_year%' ) == false )
        return $permalink;

    if ( is_object( $post ) && 'event' == $post->post_type ) {

        $default_year="1970";
        $default_month="january";

        if( $event_year = get_post_meta( $post->ID, 'event_year', true ) ){
            $permalink = str_replace( '%event_year%', $event_year, $permalink );
        } else {
            $permalink = str_replace( '%event_year%', $default_year, $permalink );
        }

        if( $event_month = get_post_meta( $post->ID, 'event_month', true ) ){
            $permalink = str_replace( '%event_month%', $event_month, $permalink );
        } else {
            $permalink = str_replace( '%event_month%', $default_month, $permalink );
        }

    }

    return $permalink;
}

add_filter( 'post_type_link', 'wpa83531_event_post_link', 10, 3 );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)