Set WordPress Permalink Setting When Plugin Activated
Wanted:
I want to set permalink setting to ‘/%category%/%postname%/’ when plugin activated
Known:
-
- The code in plugin_folder/admin/fahmi_tutorial_activate_permalinks.php
-
- The main plugin file is fahmi_tutorial.php
Question:
How to do it?
Answer:
Create fahmi_tutorial_activate_permalinks.php file inside plugin_folder/admin
Create a function named as fahmi_tutorial_activate_permalinks with content like below:
<?php
function fahmi_tutorial_activate_permalinks() {
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%category%/%postname%/');
flush_rewrite_rules(true);
}
$main_file = dirname(dirname(__FILE__)) . '/fahmi-tutorial.php';
register_activation_hook( $main_file, 'fahmi_tutorial_activate_permalinks' );
Explain:
-
- $wp_rewrite->set_permalink_structure: this code is use to update options wordpress table, which option_name permalink_structure updated with ‘/%category%/%postname%/’ option value
-
- flush_rewrite_rules(true): this code is use to update options wordpress table in rewrite_rules option_name
-
- $main_file is required because register_activation_hook() function must be run inside main file of plugin
-
- register_activation_hook( $main_file, ‘fahmi_tutorial_activate_permalinks’ ): this code is use to run fahmi_tutorial_activate_permalinks function when plugin activated