Search code examples
phpwordpresspermalinks

Wordpress - page_link filter


I'm trying to change default pages post type permalink, I'd like to add a '.php' to its end for example: home_url() . post_name . '.php'

I can't use WordPress permalinks page because I'm using it already like this: /%category%/%postname%.php and this doesn't affect the default pages post type.

So I did it like follows:

function wp_pages_permalink( $permalink, $post_id ) {
    if ( empty( $post_id ) ) return $permalink;

    $post = get_post( $post_id );

    return home_url( $post->post_name . '.php'  );
}

add_filter( 'page_link', 'wp_pages_permalink', 10, 2 );

However I get a 404 when I try to visit the page, and I have already flushed the rewrite rules by visiting the permalinks page.


Solution

  • As suspected, this needed a rewrite rule.. I don't know why post_link filter didn't need a rewrite rule added..

    function ba_rewrite() {
        add_rewrite_rule('^([^/]*)?.php', 'index.php?pagename=$matches[1]', 'top');
    }
    
    add_action( 'init', 'ba_rewrite' );