I’m trying to insert posts using a cron job, but I keep running into errors where WP is missing functions (is_user_logged_in, wp_get_current_user).

Is there a proper way to run wp_insert_post using a cron job?

This is the code I have so far.

phrets_hourly is the WP_CRON hook

add_action('phrets_hourly', 'run_listings_update' );

function run_listings_update(){
  $fetch = new Fetcher();
  $fetch->fetch();
}

This is the code inside the $fetch object (Fetcher class) that is run.

public function fetch(){
  $options['class'] = 'RES';
  $options['limit'] = 10;
  $options['offset'] = 0;
  $options['silent'] = true;     
  $data = $this->query( $options );
  foreach ( $data as $datum ) {
    $this->place( $datum, true );
  }
}

public function place( $data, $silent ){
  $rets = $this->connect_to_rets();
  $listing = new Listing( $data );
  // check to see if listing already exists
  $post_id = $listing->check_listing_exists( $data['MST_MLS_NUMBER'] );
  if ( ! $post_id ) {
    $action = $listing->put();
  } else {
    $action = $listing->update($post_id);
  }
}

This is the method called from the $listing object (Listing class) that puts the data into the DB

public function put(){
  $title = $this->create_title( $this->data );
  // setup the 'post' data
  $post = array(
    'post_type' => 'listing',
    'post_title' => $title,
    'post_content' => $this->data['Remarks'],
    'post_status' => 'publish'
  );
  // add new meta data
  if ( ! is_wp_error( $post_id ) ) {
    $this->add_meta_data( $post_id );
    $this->assign_community( $post_id, $data );
  }
  // set the action
  $action = 'inserted';
  return $action;
}

Thanks!

2 Answers
2

For those who stumble upon this later, use either option 1 or 2 found here: https://core.trac.wordpress.org/ticket/19373.

“For other developers who run into this and need to work around it, either of these 2 options work:
call wp_set_post_terms() to add your taxonomies after calling wp_insert_post()
set up a “current user” in your script before calling wp_insert_post()”

Leave a Reply

Your email address will not be published. Required fields are marked *