wp_insert_post creates multiple pages

I have a function in functions.php which automatically generates a page. It doesn’t check to see if there is already a page with the same title at the moment.

The function is started with:

add_action( 'after_setup_theme', 'add_pages' );

edit: I only want this to run once every page load.
I think it is the same thing if I would use

add_action( 'init', 'add_pages' );

Here is the code in the add pages function:

function add_pages() {

    $content = "text content";

    $page = array(
        'post_title' => 'A unique title?',
        'post_content' => $content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'page',
        'post_parent' => 0 
    );


    // Add page
    $insert_id = wp_insert_post( $page );
}

When I reload the “posts” page in wordpress admin, two new pages are created. When I reload again, four new pages are created. When I reload again, a whole
bunch of pages are created. I was wondering if there is an explanation for this?

edit: If I change the post_title and reload, only one page is created. But if I reload again, two pages are created. But after that, it behaves irrationally, sometimes there are consistently two pages created on each page load , but sometimes a large number of pages are created.

I intend to check if the page title already exists, but I wanted to understand this behaviour anyway.

2 Answers
2

after_setup_theme is not the hook you are looking for – you want after_switch_theme – this hook will only run once, when your theme is initally activated.

Leave a Comment