Custom Permalink for listing pages

HI,
I am aiming to set up the permalink format as example.com/state/city/title, where ‘state’ and ‘city’ are custom attributes of the listings.

I have implemented the following code to achieve this:

// Register custom rewrite tags
function custom_hivepress_rewrite_tags() {
    add_rewrite_tag('%company_state%', '([^/]+)');
    add_rewrite_tag('%company_city%', '([^/]+)');
}
add_action('init', 'custom_hivepress_rewrite_tags');

// Custom rewrite rules for listing as state/city/title
function custom_hivepress_rewrite_rules() {
    add_rewrite_rule(
        '^([^/]+)/([^/]+)/([^/]+)/?$',
        'index.php?post_type=hp_listing&name=$matches[3]&company_state=$matches[1]&company_city=$matches[2]',
        'top'
    );
}
add_action('init', 'custom_hivepress_rewrite_rules');

// Filter to modify the post type link
function custom_hivepress_listing_link($post_link, $post) {
    if ($post->post_type === 'hp_listing') {
        $listing = HivePress\Models\Listing::query()->get_by_id($post->ID);
        $company_state = $listing->get_company_state();
        $company_city = $listing->get_company_city();

        if ($company_state && $company_city) {
            $post_link = str_replace('%company_state%', $company_state, $post_link);
            $post_link = str_replace('%company_city%', $company_city, $post_link);
        }
    }
    return $post_link;
}
add_filter('post_type_link', 'custom_hivepress_listing_link', 10, 2);

// Ensure the rewrite rules are flushed on theme activation
function custom_hivepress_flush_rewrite_rules() {
    custom_hivepress_rewrite_rules();
    flush_rewrite_rules();
}
add_action('after_switch_theme', 'custom_hivepress_flush_rewrite_rules');

While the custom URL structure is working as expected when accessed directly as https://nationalprobateservices.com/WY/Cheyenne/brian-c-shuck/, there is an issue when clicking on a listing from the listings page. The URL redirects to https://nationalprobateservices.com/listing/brian-c-shuck/ instead of the desired format.

Refer: Customize the permalink structure for listings

Hi,

Links within the listing block use the core WordPress function get_permalink hivepress/includes/controllers/class-listing.php at master · hivepress/hivepress · GitHub Please make sure that these code changes also cover the link generation via the get_permalink based on this new custom structure.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.