0

i'm trying to import data from table to custom post types below is the code i'm using but this $row['Title'] return nothing ... if i hard code it works

$rows = $wpdb->get_results( "SELECT * FROM Products");

  foreach ($rows as $row) 
      {

      $new_post = wp_insert_post(array(
      'post_type' => 'products', 
      'post_status' => 'publish',
      'post_author' => $authorID,
      'post_title'  => $row['Title']
      ));

      if( !is_wp_error($new_post) )
        {

          update_post_meta($new_post, "shakamaka", $row['DocFileID']);

        }

};

1 Answer 1

1

$row doesn't look like you think it does. $wpdb->get_results will by default return an array of objects. Your code-- 'post_title' => $row['Title']-- treats an object like an array and should generate a Fatal Error, which you'd see if you had debugging enabled.

Fatal error: Cannot use object of type stdClass as array in ...

You need object syntax. Try (using a Core table):

$rows = $wpdb->get_results( "SELECT * FROM wp_posts");
foreach ($rows as $row) {
  // echo $row['post_author']; // doesn't work
  echo $row->post_author; // works
  echo '<br>';
}
2
  • Thanks a lot S_HA_DUM, how should i have known this that $wpdb->get_results is returning an array of objects ?
    – Yasir
    Commented Jun 14, 2014 at 15:02
  • You could read the Codex to start, or just dump the data and look at it-- var-dump($rows)-- both pretty basic development/debugging steps.
    – s_ha_dum
    Commented Jun 14, 2014 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.