Wordpress rewrite add base prefix to pages only

2020-07-27 04:18发布

问题:

I have a problem I've encountered when trying to finish a project.

  1. I have the current permalink structure set as /%postname%/
  2. I made my own function on giving a prefix to posts only so my posts are rewritten as /{prefix}/%postname%/.

My problem is that I want to change the permalink of the pages as I did with the posts so my pages will have a prefix like /{prefix}/%pagename%/.

What I tried and didn't work:

  1. Re-declare the PAGES post type and set a rewrite slug.
  2. Tried adding a custom rewrite rule as a function but it didn't work:

    $rewrite_rules += array('mycustomprefix/(.+?)/([0-9]+)/([^/]+)/([^/]+)/?$' =>'index.php?pagename=$matches[1]',

Is this possible? Are there any developers out there who encountered the same issue?

回答1:

For anybody interested, I've fixed my issue in the following manner:

function change_author_permalinks() {
global $wp_rewrite;
// Change the value of the author permalink base to whatever you want here
$wp_rewrite->author_base = '';
// Change the value of the page permalink base to whatever you want here
$wp_rewrite->page_structure = 'static/%pagename%';
$wp_rewrite->flush_rules();
}
add_action('init','change_author_permalinks');

Hope this helps others as I couldn't find any help for this anywhere. For morer information on what you can change this way, check out http://codex.wordpress.org/Class_Reference/WP_Rewrite



回答2:

Have you updated the permalinks structure after adding this rewrite to your functions.php ? It works for me :)

add_filter( 'page_rewrite_rules', 'customprefix_page_rewrite_rules' );
function customprefix_page_rewrite_rules( $rewrite_rules )
{
    end( $rewrite_rules );
    $last_pattern = key( $rewrite_rules );
    $last_replacement = array_pop( $rewrite_rules );
    $rewrite_rules +=  array(
        'mycustomprefix/(.+?)/?$' => 'index.php?pagename=$matches[1]',
        $last_pattern => $last_replacement,
    );
    return $rewrite_rules;
}


回答3:

I found this solution working for me better... and it's also much cleaner code.

add_action( 'init', 'custom_page_rules' );

function custom_page_rules() {
  global $wp_rewrite;
  $wp_rewrite->page_structure = $wp_rewrite->root . 'your-page-prefix/%pagename%'; 
}

I found the code here: http://wpforce.com/change-wordpress-page-permalinks/