The routine below inserts a page, sets permalinks to postname then attempts to update the permalinks settings.
However, when I view the newly created page, I still get a 404 error. The only way to make it go away is to hit the settings > permalinks manager (just merely accessing the page does the trick, i don’t even have to save).
What’s up with that?
//create and insert a post
$my_post['post_content'] = "This is the content";
$my_post['post_type'] = 'page';
$my_post['post_status'] = 'publish';
wp_insert_post($my_post);
// Including files responsible for .htaccess update
require_once(ABSPATH . ‘wp-admin/includes/misc.php’);
require_once(ABSPATH . ‘wp-admin/includes/file.php’);
// Prepare WordPress Rewrite object in case it hasn't been initialized yet
if (empty($wp_rewrite) || !($wp_rewrite instanceof WP_Rewrite))
{
$wp_rewrite = new WP_Rewrite();
}
// Update permalink structure
$permalink_structure = '/%postname%/';
$wp_rewrite->set_permalink_structure($permalink_structure);
// Recreate rewrite rules
$wp_rewrite->flush_rules();
Where is your code, in a plug-in or a theme?
The following plug-in works for me in the latest version of WP. It won’t work if
.htaccessis not writeable, but I don’t think you can do anything about that.