Wordpress - How Do I Programmatically Force Custom Permalinks with My Theme?

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

You may not need the action hook if you're sticking this in your theme activation function code.

I also found that this only slightly worked. You still have to click the Permalinks settings page for that .htaccess file to be created. So, what to do? Well, I found I could use an IFRAME that loads that page automatically for me from my theme's options panel, and then it would create that .htaccess file for me.

<iframe style="position:absolute;top:-5000px" src="<?= site_url() ?>/wp-admin/options-permalink.php"></iframe>

To fully enable permalinks, you also need to ensure that .htaccess is also created. To do that, you need to set an option and flush the rules with a Boolean.

global $wp_rewrite; 

//Write the rule
$wp_rewrite->set_permalink_structure('/%postname%/'); 

//Set the option
update_option( "rewrite_rules", FALSE ); 

//Flush the rules and tell it to write htaccess
$wp_rewrite->flush_rules( true );

If you use this in a plugin, it needs to be in the init hook, not the load hook. If it's in the load hook, it will throw an error saying $wp_rewrite is null.

Important: You should also have a conditional so this is only set once. (You can create an option and check if it's set, if not then you run this permalink code and set that option)

I also typically check if it's the admin side and only run it if it is.