phpwordpresspermalinks

Changing permalinks via functions.php


I have designed a wordpress theme where I have designed a separate page for users to log in and this page will be accessible if permalinks are selected as %pagename% %category%.

For this, I know that I have to select the permanent link I want through the WordPress settings and from the unique links tab.

But I want to put a piece of code inside the functions.php file so that it will be done automatically after the user activates the WordPress theme and the previously selected links will be disabled.

I have used the following code but it did not change the permalink:

/*
 * Set permlinks on theme activate
 */
    function set_custom_permalinks() {
        $current_setting = get_option('permalink_structure');

        // Save permalinks to a custom setting, force create of rules file
        global $wp_rewrite;
        update_option("rewrite_rules", FALSE);
        $wp_rewrite->set_permalink_structure('/%postname%/%category%/');
        $wp_rewrite->flush_rules(true);
    }
    add_action('after_switch_theme', 'set_custom_permalinks');

Edit:

After a bit of searching, I found out that permalinks can be edited through the database in addition to the WordPress settings.

To change the permanent links through the database, I went to the following path:

1- I clicked on wp_options in the database

2- Under option_name, I looked for the permalink_structure table.

3- After finding the permalink_structure table, I clicked on the edit option.

4- Then in the option_value field, I entered my permanent link as follows:

/%postname%/%category%/

After completing the above steps, the permanent link of my site was changed correctly.

Now I want a code that can do this for me.


Solution

  • I achieved what I wanted by using the following code and my site's permalinks were sorted correctly:

    function custom_permalinks() {
       global $wp_rewrite; 
        
    $wp_rewrite->set_permalink_structure('/%postname%/%category%/'); 
    
    update_option( "rewrite_rules", FALSE ); 
    
    $wp_rewrite->flush_rules( true );
    }
    
    add_action( 'init', 'custom_permalinks' );
    

    By placing the above code in the functions.php file, the site's permanent links will be arranged as you wish, and the user cannot change your permanent link through the WordPress settings under any circumstances.