I am trying to create a custom post type called an 'event' and have it's permalink structure be as follows:
www.domain.com/events/238
where 238 is the post ID. However, when I navigate to the page, I get a 'no results found' page.
Here is my code (I abbreviated the register_post_type call to include only the important elements).
add_action( 'init', 'initialize'));
function initialize() {
register_post_type('event',
array(
'labels' => array('name' => 'Events'),
'public' => true,
'publicly_queryable' => true,
'query_var' => true,
'rewrite' => false,
'show_ui' => true,
'has_archive' => true
)
);
global $wp_rewrite;
$event_structure = '/events/%event_id%';
$wp_rewrite->add_rewrite_tag("%event_id%", '([0-9]+)', "event_id=");
$wp_rewrite->add_permastruct('event', $event_structure, false);
}
add_filter('post_type_link', 'handle_permalink', 10, 3);
function handle_permalink( $permalink, $post_id, $leavename ) {
$post = get_post($post_id);
if ( $post->post_type == jp_event::POST_TYPE ) {
$rewritecode = array( '%event_id%' );
$rewritereplace = array($post->ID);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
return $permalink;
}
return $permalink;
}
How do I make this code work? What am I doing wrong?
Settings > Permalinks
screen in your admin area, and save your permalink structure (even if you make no changes to it). This should flush your permalink structure. See the note at codex.wordpress.org/Rewrite_API/flush_rules .'rewrite' => false
in yourregister_post_type()
and then try to recreate the permalink in another function? If not, try passing an array into therewrite
argument as detailed in the Codex page.