title: Wordpress trying to use wp_insert_post for new posts and wp_update_post for post updates - need post ID?
body: <p>I am building a Wordpress site where we want to automatically populate wordpress posts from an EXTERNAL (not wordpress) database.  I have already created a code that successfully checks the external database for post title and if it is not found, creates the post.  This is great, but I am also trying to "update" the post if the title is found.  I have attempted to update my code to do this, but when run the code in my plugin I get an error that says</p>
  
  <pre><code>Notice: Undefined variable: page_name in /var/www/html/dev2/wp-content/plugins/hello/hello.php on line 54 Fatal error: Cannot redeclare get_page_id() (previously declared in /var/www/html/dev2/wp-content/plugins/hello/hello.php:49) in /var/www/html/dev2/wp-content/plugins/hello/hello.php on line 49
  </code></pre>
  
  <p>Can anyone help me fix my code to insert NEW posts and update OLD posts?  Here is my code, your expertise is much appreciated!!!</p>
  
  <pre><code>&lt;?php
  /*
  Plugin Name: Post Updater
  Plugin URI: http://wordpress.org/
  Description: 
  Author: Matt
  Author URI: 
  Version: 2.3
  Text Domain: 
  License: GPLv2 or later
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
  */
  
  // Add Shortcode
  function hello() {
  
      // Code
  global $wpdb;
  
  $sql = &lt;&lt;&lt;SQL
  SELECT cool_name, cool_content
  FROM cool_test.cool_table 
  SQL;
  
  
  
  
  $rebates = $wpdb-&gt;get_results( $sql );
  foreach ( $rebates as $rebate ){
      $new_post = array(
          'post_title' =&gt; $rebate-&gt;cool_name,
          'post_content' =&gt; $rebate-&gt;cool_content,
          'post_status' =&gt; 'publish',
          'post_date' =&gt; date('Y-m-d H:i:s'),
          'post_author' =&gt; 31,
          'post_type' =&gt; 'post',
          'post_category' =&gt; array(10)
      );
      $page_exists = get_page_by_title( $rebate-&gt;cool_name, OBJECT, 'post' );
  
      if( $page_exists == null ) {
          // Page doesn't exist, so lets add it
          $insert = wp_insert_post( $new_post );
          if( $insert ) {
              // Page was inserted 
          }
      } else {
          // Page already exists
          function get_page_id($page_name){
      global $wpdb;
      $page_name = $wpdb-&gt;get_var("SELECT ID FROM $wpdb-&gt;posts WHERE post_name = '".$page_name."'");
  }
          $updatePost = array(
        'ID'           =&gt; $page_name,
        'post_content' =&gt; $rebate-&gt;cool_content
    );
  
  // Update the post into the database
    wp_update_post( $updatePost );
      }
  
  
  }
  
  
  }
  add_shortcode( 'hello', 'hello' );
  
  ?&gt;
  </code></pre>