Wordpress trying to use wp_insert_post for new posts and wp_update_post for post updates - need post ID?


Staff member
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

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

Can anyone help me fix my code to insert NEW posts and update OLD posts? Here is my code, your expertise is much appreciated!!!

Plugin Name: Post Updater
Plugin URI: http://wordpress.org/
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 = <<<SQL
SELECT cool_name, cool_content
FROM cool_test.cool_table 

$rebates = $wpdb->get_results( $sql );
foreach ( $rebates as $rebate ){
    $new_post = array(
        'post_title' => $rebate->cool_name,
        'post_content' => $rebate->cool_content,
        'post_status' => 'publish',
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => 31,
        'post_type' => 'post',
        'post_category' => array(10)
    $page_exists = get_page_by_title( $rebate->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->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$page_name."'");
        $updatePost = array(
      'ID'           => $page_name,
      'post_content' => $rebate->cool_content

// Update the post into the database
  wp_update_post( $updatePost );


add_shortcode( 'hello', 'hello' );