Hi @wpbroken2much
You can flush the permalinks from your plugin activation hook by calling the flush_rewrite_rules function. This function flushes the rewrite rules and updates the .htaccess file if needed.
Here’s an example of how you can use it in your plugin activation hook:
function my_plugin_activate() {
// ... do other things in the activation hook
// Flush rewrite rules
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'my_plugin_activate' );
You can also use the register_activation_hook function to register your activation hook. This function takes two arguments: the path to your plugin file and the function’s name to be called when the plugin is activated.
Note that you should only flush the rewrite rules when you’re adding or modifying rewrite rules. If you don’t need to add or modify any rewrite rules, you don’t need to flush the rewrite rules.
I hope this helps! Let me know if you have any questions.
Thanks, now I just need to figure out how to submit the rules via the API I guess. I already have an activation hook in the plugin but I’m not really sure how to submit the new rules via the API. The examples used by WP are slim and all involve regular expressions other than ones which would work in my situation.
I need users to be able to visit something like example.com/folder/{0-9} but have the site serve the content from example.com/wp-content/plugins/myplugin/folder/index.php?id={0-9}. Could you please create an example that would work for those types of URLs exactly?
Hi @wpbroken2much
Sure, here’s an example of how you can use the add_rewrite_rule function to create custom rewrite rules for your plugin:
function my_plugin_activate() {
// Your existing activation code goes here...
// Add a rewrite rule
add_rewrite_rule(
'^folder/(\d+)/?',
'wp-content/plugins/myplugin/folder/index.php?id=$matches[1]',
'top'
);
// Flush the rewrite rules
flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'my_plugin_activate');
This will create a rewrite rule that matches URLs like example.com/folder/123, and rewrite them to example.com/wp-content/plugins/myplugin/folder/index.php?id=123. The $matches[1] variable in the target URL will be replaced with the value of the first captured group in the regex pattern (in this case, the folder ID).
I hope this helps! Let me know if you have any other questions.