Add .html permalink to post if specific category

I followed this helpful guide (update 2)

Giving specific category posts its own permalink structure returns 404

that creates the following permalink if the category “Foodguide” is selected:

/foodguide/25/post name slug.html (Category/post Id/post name.html)

Here is the code that I am using in functions.php:

//Rewrite URLs for Foodguide category
add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
    // Get the category for the post
    $category = get_the_category($post-ID);
    if (  !empty($category)  $category[0]-cat_name == Foodguide ) {
        $cat_name = strtolower($category[0]-cat_name);
        $permalink = untrailingslashit( home_url( '/'. $cat_name . '/' . $post-ID . '/' . $post-post_name . '.html' ) );
    }
    return $permalink;
}

add_filter( 'category_link', 'custom_category_permalink', 10, 2 );
function custom_category_permalink( $link, $cat_id ) {
    $slug = get_term_field( 'slug', $cat_id, 'category' );
    if ( ! is_wp_error( $slug )  'foodguide' === $slug ) {
        $link = home_url( user_trailingslashit( '/foodguide/', 'category' ) );
    }
    return $link;
}

add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
    add_rewrite_rule(
        'foodguide(?:/page/?([0-9]{1,})|)/?$',
        'index.php?category_name=foodguidepaged=$matches[1]',
        'top' // The rule position; either 'top' or 'bottom' (default).
    );

    add_rewrite_rule(
    '^foodguide/(\d+)/[^/]+\.html$',
    'index.php?category_name=foodguidep=$matches[1]',
    'top'
);
}
function cancel_canonical_redirect( $wp ) {
    if ( '^foodguide/(\d+)/[^/]+\.html$' === $wp-matched_rule ) {
        remove_action( 'template_redirect', 'redirect_canonical' );
    }
}
add_action( 'parse_request', 'cancel_canonical_redirect' );

The change that I need is the following:

When category “Foodguide” is selected, I want to show domain.com/postname.html (No category or post id)

Appreciate any help.

Topic permalinks Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.