remove post-name from title in custom post type

Fixing the 404 error

So it’s because of the ([^&]+) in your add_rewrite_tag() calls:

$wp_rewrite->add_rewrite_tag('%reference%', '([^&]+)', 'reference=");
//$wp_rewrite->add_rewrite_tag("%location%', '([^&]+)', 'location=');

To fix the error, you should use ([^/]+) and not ([^&]+).

I also intentionally commented out the second line because if the taxonomy’s slug is location, then WordPress should have already added the %location% rewrite tag.

Removing the post slug from the permalink

You shouldn’t remove it from within your permalink_structure() method, which I assumed is hooked to the post_type_link filter.

Instead, you can quite easily remove the slug like so: (WordPress by default appends /%<post type slug>% to the $permastruct['struct'], so the code below removes that post slug identifier)

// Add this after the post type has been registered (after the register_post_type() call).

global $wp_rewrite;

$permastruct = $wp_rewrite->extra_permastructs['property'];
$permastruct['struct'] = str_replace( '/%property%', '', $permastruct['struct'] );
$wp_rewrite->extra_permastructs['property'] = $permastruct;

And in the permalink_structure() method, the $rewritecode should not include the post slug:

$rewritecode = array(
    '%reference%',
    '%location%',
);

$rewritereplace = array(
    $reference,
    $location,
);

Locating the correct “property”/post based on the “reference” part in the request/page path

The code below is pretty self-explanatory, but if you’ve got any questions, let me know:

add_action( 'parse_request', function( $wp ){
    // Check if the request/page path begins with /malta-property/<location>/<reference>
    if ( preg_match( '#^malta-property/([^/]+)/([^/]+)#', $wp->request, $matches ) ) {
        $posts = get_posts( [
            'post_type'      => 'property',
            'meta_key'       => 'propertystream_agent_ref',
            'meta_value'     => $matches[2],
            'posts_per_page' => 1,
        ] );

        if ( ! empty( $posts ) ) {
            $wp->query_vars['name'] = $posts[0]->post_name;
            $wp->query_vars['post_type'] = 'property'; // must set post type
        }
    }
} );

And remember to flush the rewrite rules — just visit the “Permalink Settings” page.

Also, as mentioned in my comment, I’m assuming each “property” post always has a metadata named propertystream_agent_ref and that the value is unique.

Leave a Comment