Multiple post types – share same ReWrite slug?

I’ve just done a project where two Custom Post Types needed to share the same slug. The trick is to overwrite the query vars via the request filter. Let’s call the post types ‘foo’ and ‘bar’, and they will share slug ‘foo’.

The following code is rough and from memory for example only. Salt to taste, do not copy-paste:

add_filter('request', 'overwriteQueryVars', 10, 1);

function overwriteQueryVars($query)
{
    if ( empty($query['post_type']) || $query['post_type']!='foo' ) {
        return $query;
    }

    // Run an SQL query that looks like this, against both post types
    $sql = "SELECT ID FROM wp_posts WHERE post_type="foo" and post_name="%s"";
    $post_name = urlencode($query['name']);

    // If you've found that the row exists for post_type 'bar' but not 'foo',
    // then simply return the $query array unaltered
    if ( in_foo_but_not_bar ) {
        return $query;
    }

    // If you've found that the row exists for post_type 'bar' but not 'foo',
    // then rewrite the $query array:

    // Original:
    $query = array (
        'page' => '',
        'foo' => 'some-nice-post',
        'post_type' => 'foo',
        'name' => 'some-nice-post',
    );

    // Make it look like this:
    $query = array (
        'page' => '',
        'bar' => 'some-nice-post',
        'post_type' => 'bar',
        'name' => 'some-nice-post',
    );

}

Leave a Comment