• I have been using the following code to remove my CPT slug named ‘coupon’.

    /**
     * Remove the slug from published post permalinks.
     */
    function custom_remove_cpt_slug( $post_link, $post, $leavename ) {
    
        if ( 'coupon' != $post->post_type || 'publish' != $post->post_status ) {
            return $post_link;
        }
    
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
    
        return $post_link;
    }
    add_filter( 'post_type_link', 'custom_remove_cpt_slug', 10, 3 );
    
    /**
     * Some hackery to have WordPress match postname to any of our public post types
     * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
     * Typically core only accounts for posts and pages where the slug is /post-name/
     */
    function custom_parse_request_tricksy( $query ) {
    
        // Only noop the main query
        if ( ! $query->is_main_query() )
            return;
    
        // Only noop our very specific rewrite rule match
        if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
            return;
        }
    
        // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
        if ( ! empty( $query->query['name'] ) ) {
            $query->set( 'post_type', array( 'post', 'coupon', 'page' ) );
        }
    }
    add_action( 'pre_get_posts', 'custom_parse_request_tricksy' );

    When I use the code in conjunction with your plugin I get 404 errors, but once I remove it again everything works the way it should. What is causing the conflict? There are so many rewrites that it’s hard to see where I’m going wrong! Would be cool if you could integrate an option to remove the CPT slug in the plugin itself.

    https://wordpress.org/plugins/custom-post-type-permalinks/

  • The topic ‘Remove CPT Slug Causes 404 error’ is closed to new replies.