• Ok so I have a plugin that I would like to have automatically create a page on activation, but every piece of code I have tried has yet to work. Every once in a while, it will decide to add the page, but I can never get it to repeat itself. (deleting page, deactivating, then reactivating plugin to test)

    Here are the scenerios I have tried.

    <?php
    wp_insert_post( $new_page );
    
    $new_page = array(
    'post_title' => 'Employees',
    'post_name' => 'employees',
    'post_status' => 'publish',
    'post_type' => 'page',
    'post_author' => $user_ID,
    'post_parent' => 0,
    'menu_order' => 0
    );
    
    	//if we have created any new pages, then flush...
    	if ( $newpages ) {
    		wp_cache_delete( 'all_page_ids', 'pages' );
    		$wp_rewrite->flush_rules();
    	}
      ?>
    <?php
    if ($_GET['activated']){
    
        $new_page_title = 'This is the page title';
        $new_page_content = 'This is the page content';
        $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.
    
        //don't change the code bellow, unless you know what you're doing
    
        $page_check = get_page_by_title($new_page_title);
        $new_page = array(
            'post_type' => 'page',
            'post_title' => $new_page_title,
            'post_content' => $new_page_content,
            'post_status' => 'publish',
            'post_author' => 1,
        );
        if(!isset($page_check->ID)){
            $new_page_id = wp_insert_post($new_page);
            if(isset($new_page_template)){
                update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
            }
        }
    
    }
    ?>

    And the one wordpress has posted in the codex:

    <?php
    // Create post object
      $my_post = array(
         'post_title' => 'My post',
         'post_content' => 'This is my post.',
         'post_status' => 'publish',
         'post_author' => 1,
         'post_category' => array(8,39)
         'post_type' => 'page' /* this actually makes the entire backend to disappear so I have to put it in $defaults=array( for it to reappear. The page doesn't always want to show up though.*/
      );
    
    // Insert the post into the database
      wp_insert_post( $my_post );
    ?>

    With this last bit, I can get the pages to appear, but posts are also created…I don’t need them!

  • The topic ‘wp_insert_post as page not working?!’ is closed to new replies.