The routine below card inserts a webpage, sets permalinks to postname then tries to update the permalinks configurations.

However, after i see the recently produced page, I get a 404 error. The only method to allow it to be disappear would be to hit the configurations > permalinks manager (just basically being able to access the page does the secret, i do not even need to save).

What's going on with this?

//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 accountable 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();

Merely a suggestion for you personally... Disable any WordPress cache functionality before debugging this issue. Frequently I've permalinks problems, when utilizing any Wordpress caching.

Where's your code, inside a plug-in or perhaps a theme?

The next plug-in works best for me within the latest version of Wordpress. It will not work if .htaccess isn't writeable, however i don't believe that you can do anything about this.

function my_plugin_activate() {
    $test_post = array(
        'post_title' => 'Lorem ipsum',
        'post_content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing …',
        'post_status' => 'publish',
        'post_type' => 'post'
    );
    wp_insert_post($test_post);

    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure('/%postname%/');
    $wp_rewrite->flush_rules();
}

register_activation_hook(__FILE__, 'my_plugin_activate');