0

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?

5
  • Try visiting the 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 .
    – Pat J
    Commented Apr 12, 2013 at 19:43
  • I just tried this and it still isn't working. When I'm in the edit post page, the permalink is being displayed correctly under the title but when I click 'View Event' and it takes me to the page, it says no results found (and when I remove the custom permalink logic the page resolves fine so I'm pretty sure that it is this logic that is causing the issue).
    – William
    Commented Apr 12, 2013 at 19:48
  • Do you have a caching plugin? if so, flush the cache.
    – vancoder
    Commented Apr 12, 2013 at 19:57
  • Is there a compelling reason to set 'rewrite' => false in your register_post_type() and then try to recreate the permalink in another function? If not, try passing an array into the rewrite argument as detailed in the Codex page.
    – Pat J
    Commented Apr 12, 2013 at 20:09
  • I'm not really clear what you are suggestion - you think I should just put /events/%event_id% in as a parameter of 'rewrite'? I just tried and it doesn't seem to be working -
    – William
    Commented Apr 13, 2013 at 2:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.