• Resolved tgeddy

    (@tgeddy)


    I have custom fields called “games” and I want their permalinks to be example.com/game-name.

    If I change the WordPress permalink setting to post name, I get example.com/games/game-name. If I change the custom rewrite slug setting in cpt ui to %postname%, I get example.com/game-name/game-name. How can I get it to be example.com/game-name? Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Contributor Michael Beckwith

    (@tw2113)

    The BenchPresser

    That’s a topic that CPTUI doesn’t attempt to cover, as it gets into the rewrite rules API and customizing permalinks at a higher level. One thing to keep in mind is that the “game-name” first part of the URL is helping with the querying, telling WordPress to only look at the “game-name” post type slug, instead of having to look at ALL rows in the posts table.

    I know there are tutorials out there for the topic, but it’s simply not something our UI will cover.

    function remove_cpt_slug( $post_link, $post, $leavename ) {
     
        if ( 'games' != $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', 'remove_cpt_slug', 10, 3 );
    
    function gparse_request_trick( $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', 'page', 'games' ) );
        }
    }
    add_action( 'pre_get_posts', 'parse_request_trick' );
    
    • This reply was modified 9 years, 4 months ago by freehack.
    • This reply was modified 9 years, 4 months ago by freehack.
Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Custom permalink with only post name’ is closed to new replies.