skip to Main Content

I’m having trouble creating a custom URL for certain single post types. whereas it works for posts. Here is my code to change the URL of only certain posts:

/**
 * Rewire the permalink of individual posts so that they direct to the Free Cakes section
 */
add_filter( 'post_link', 'ae_replace_freecakes_posts_link', 90, 2 );

function ae_replace_freecakes_posts_link( $permalink, $post ) {

    global $freecakes_blog_page_id;

    if ( ae_get_post_acces_level( $post->ID ) >= 110 ) {
        return get_permalink( $freecakes_blog_page_id ) . "$post->ID/{$post->post_name}/";
    }

    return $permalink;
}

/**
 * Rewire the permalink of individual videos so that they direct to the Free Cakes section
 */
add_filter( 'post_type_link', 'ae_replace_freecakes_videos_link', 90, 2 );

function ae_replace_freecakes_videos_link( $permalink, $post_object ) {

    global $freecakes_video_page_id;

    if ( $post_object->post_type != 'video' ) {
        return $permalink;
    }

    if ( ae_get_post_acces_level( $post_object->ID ) >= 110 ) {
        return get_permalink( $freecakes_video_page_id ) . "$post_object->ID/{$post_object->post_name}/";
    }

    return $permalink;
}

And later this:

add_action( 'init', 'ae_add_rewrite_rules' );

function ae_add_rewrite_rules() {
    add_rewrite_rule( "^freecakes/video/([0-9]+)/([^/]*)/?$", 'index.php?p=$matches[1]', 'top' );
    add_rewrite_rule( "^freecakes/posts/([0-9]+)/([^/]*)/?$", 'index.php?p=$matches[1]', 'top' );
}

The problem is that this doesn’t work for videos. If I use this fictional exemplary url it works just fine:

https://mywebsite.com/freecakes/posts/3892/my-first-frecake-post/

But this URL (the one matched to the video custom post type) gives a 404 error:

https://mywebsite.com/freecakes/posts/10109/my-first-frecake-video/

Any clues of what might be my mistake here? Thank you!

2

Answers


  1. Chosen as BEST ANSWER

    As it turns out, even though calling https://mywebsite.com/index.php?p=10109 would normally work while using the navigation bar, it doesn't work for custom post types when using add_rewrite_rule

    The rule that works is:

    add_rewrite_rule( "^freecakes/posts/([0-9]+)/([^/]*)/?$", 'index.php?video=$matches[2]', 'top' );
    

    Where $matches[2] is the slug of the custom post type (in this case a post_type called "video")


  2. Did you flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search