Advertisement
danhgilmore

add image to post/db

Apr 8th, 2015
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | None | 0 0
  1. /*
  2. *  In WordPress Multisite, when an image is added to a blog post in edit mode, I need to add it to the DB as a post.
  3. *  For some reason, it adds the post as an attachment to wp_1_posts instead of the correct blog's table.
  4. */
  5.  
  6. /*
  7. *   all of these variables are set, and correct
  8. */
  9.  
  10. $imgurl     = $_POST['imgurl'];
  11. $imgh       = $_POST['imgh'];
  12. $imgw       = $_POST['imgw'];
  13. $blog_id    = $_POST['blog_id'];   //    on my test box, this value is 37
  14. $post_id    = $_POST['post_id'];
  15.  
  16.  
  17. //  Switching to the blog that I want to add the image to
  18.  
  19. //switch_to_blog($blog_id);  //  <---  Verified blog_id is 37
  20.  
  21. //$wpdb->set_blog_id(37);      //  <----  This actually switches to blod id 37
  22.  
  23.  
  24. // Array of data about the image. These are the four required keys
  25.  
  26. $attachment = array(
  27.     'post_mime_type'    => 'image/jpeg',
  28.     'post_title'        => 'image title',
  29.     'post_content'      => '',
  30.     'post_status'       => 'attachment'
  31. );
  32.  
  33. //  Insert the attachment into the DB. Returns the post_id of the post
  34.  
  35. $attach_id = wp_insert_attachment($attachment, '', $_POST['post_id'] );
  36.  
  37. if ($attach_id == 0)
  38. {
  39.     //  TODO: ADD ERROR HANDLING
  40. }
  41.  
  42. // Build the HTML that will go into the draft post
  43.  
  44. $ret_url = '<a href="' . $imgurl . '"><img class="alignnone size-medium wp-image-' . $attach_id . '" src="' . $imgurl .'" alt="" width="' . $imgw . '" height="' . $imgh . '" /></a>';
  45.  
  46. // Return the HTML & die
  47. echo $ret_url;
  48.  
  49. restore_current_blog();
  50.  
  51. die();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement