When and Where to use wp_insert_post()

Use some type of conditional tag to check if those posts exist or not. If they do not exist, have them created with wp_insert_post. Do this logic inside the AddMyPages function and not around the add_action function.

Example

You want to add a page with a parent ID only if it does not exist, and want this page to always exist. Since it’s in the init hook, it’ll always check if that page exists, so it’s not really recommended to do it this way. You should actually do this on activation of a plugin (so I’ve edited my answer for that method).

register_activation_hook( __FILE__, 'AddThisPage' );

function AddThisPage() {
    global $wpdb; // Not sure if you need this, maybe

    $page = array(
        'post_title' => 'My post',
        'post_content' => 'This is my post.',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'page',
        'post_parent' => 3 // ID of the parent page
    );

    $page_exists = get_page_by_title( $page['post_title'] );

    if( $page_exists == null ) {
        // Page doesn't exist, so lets add it
        $insert = wp_insert_post( $page );
        if( $insert ) {
            // Page was inserted ($insert = new page's ID)
        }
    } else {
        // Page already exists
    }

}

Thanks @kaiser for reminding me, register_activation_hook only runs in plugins, not themes.

As for a theme, well I don’t know of an official activation hook, just switch_theme but that is run before the theme is active. I found a workaround here but it may be out of date, could be something useful to look into.

Resources used

wp_insert_post, get_page_by_title, register_activation_hook

Leave a Comment