How to set permalink structure via functions.php

I’m setting up a WordPress Network and wanted all new sites to have the same permalink structure (i.e. “/%year%/%monthnum%/%postname%/”). I’m wondering if this is possible to do via hooks or hacks in functions.php, without having to rely on users to choose that structure.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can set the permalink structure by calling on the set_permalink_structure() method of the global $wp_rewrite object.

add_action( 'init', function() {
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%postname%/' );
} );

Here’s a PHP < 5.3 version of the code in case you’re getting errors.

function reset_permalinks() {
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%postname%/' );
}
add_action( 'init', 'reset_permalinks' );

Method 2

Previous Answer is not working. I have gotten a pure solution. Can use
Use this code. It will work 100%. Thanks

/**
 * Rewrite set up, when theme activate i mean
 */
if (isset($_GET['activated']) && is_admin()) {
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure('/%postname%/');
    $wp_rewrite->flush_rules();
}

/**
* Redirect to Permalink setting Page.
* Otherwise Redirect rule will not work Properly.
*/
function redirect_to_permalink() {

    wp_redirect('options-permalink.php');
}
add_action( 'after_switch_theme', 'redirect_to_permalink' );

Method 3

function setPermaLink(){
    $ps = '/%category%/%postname%/';
    $permalink_structure = sanitize_option( 'permalink_structure', $ps);
    $blog_prefix = '/blog';
    $prefix = '/index.php';

    if ( ! empty( $permalink_structure ) ) {
        $permalink_structure = preg_replace( '#/+#', '/', '/' . str_replace( '#', '', $permalink_structure ) );
        if ( $prefix && $blog_prefix ) {
            $permalink_structure = $prefix . preg_replace( '#^/?index.php#', '', $permalink_structure );
        } else {
            $permalink_structure = $blog_prefix . $permalink_structure;
        }
    }

    $wp_rewrite->set_permalink_structure( $permalink_structure );
    flush_rewrite_rules();
}

setPermaLink();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x