最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Add rewrite rule to account for dynamically changed page titles - Stack Overflow

programmeradmin0浏览0评论

I have a property website which by default outputs property page urls like this:

/

I have some php that uses 'post_type_link' to automatically update the urls replacing the last word in this case 'London' with the property postcode which returns it as:

/

Which is loosely based on the documentation for the plugin it uses here:

This works and updates the links and urls throughout the site but the issue is when I visit the page I get a 404 page not found error.

Struggling to see why but obviously something to do with the add rewrite rule.

Any help would be hugely appreciated, thank you

add_filter( 'post_type_link', 'customise_property_post_type_link', 10, 4 );
function customise_property_post_type_link( $post_link, $post, $leavename, $sample ) {
    if ( get_post_type( $post->ID ) == 'property' ) {
        // Retrieve the postcode from the post meta
        $meta_data = get_post_meta( $post->ID );
        $postcode = isset( $meta_data['_address_postcode'][0] ) ? sanitize_title( $meta_data['_address_postcode'][0] ) : '';

        // Ensure a valid postcode is available
        if ( ! empty( $postcode ) ) {
            // Remove hyphens from the postcode
            $postcode = str_replace( '-', '', $postcode );

            // Extract the last segment of the URL (the part after the last "/")
            $post_link = preg_replace_callback(
                '/([^\/]+)\/$/',
                function ( $matches ) use ( $postcode ) {
                    // Replace only the last word in the segment
                    return preg_replace( '/[^-]+$/', $postcode, $matches[1] ) . '/';
                },
                $post_link
            );
        }
    }
    return $post_link;
}

add_action( 'init', 'rewrites_init' );
function rewrites_init() {
    // Add rewrite rule for property pages with a postcode
    add_rewrite_rule(
        '^property/([^/]+)-([^/]+)/?$',
        'index.php?post_type=property&name=$matches[1]',
        'top'
    );
    flush_rewrite_rules();
}
发布评论

评论列表(0)

  1. 暂无评论