how to add posts with image programmatically in wordpress - php

This the code to add a post programmatically in wordpress
require(dirname(__FILE__) . '/wp-load.php');
global $user_ID;
$new_post = array(
'post_title' => 'Table Tennis',
'post_content' => 'Table tennis or ping-pong is a sport in which two or four players hit a lightweight ball back and forth using a table tennis racket. The game takes place on a hard table divided by a net. Except for the initial serve, players must allow a ball played toward them only one bounce on their side of the table and must return it so that it bounces on the opposite side. Points are scored when a player fails to return the ball within the rules.',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(2),
);
$post_id = wp_insert_post($new_post);
how to add image to the post?
i am new to wordpress,thanks in advance..

This will upload the file using WordPress and then insert it on the post as a featured image.
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $thumbnail, $post_id );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $thumbnail );
wp_update_attachment_metadata( $attach_id, $attach_data );
// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id);

Related

Using wp_insert_post() and wp_insert_attachment() at the same time

I am working on migrate blog posts, which are more than 1000 posts, from an old custom database website to wordpress. After formatted each post with php array, I am testing how to migrate them to wordpress.
What I want to do is migrate blog posts with featured images. After some research, I used wp_insert_post() which worked just with the text contents> However it does not insert featured images, so I need to use wp_insert_attachnment() as well. The problem is when I use wp_insert_post() and wp_insert_attachnment() together, inside foreach loop, it does not work well. The code I have is below. If anyone has knowledge/approach about this issue, please give me advice. Thank you.
$wp_posts = array(
array(
'post_id' => '10',
'post_title' => 'Post Title 1',
'post_date' => '2015-06-22',
'post_content' => 'Post Content 1',
'post_imagePath' => 'http://localhost/test/wp-content/uploads/2016/01/image1.jpg'
),
array(
'post_id' => '11',
'post_title' => 'Post Title 2',
'post_date' => '2015-06-22',
'post_content' => 'Post Content 2',
'post_imagePath' => 'http://localhost/test/wp-content/uploads/2016/01/image2.jpg'
)
);
$filetype['type'] = 'image/jpeg';
$last = count($wp_posts) - 1;
foreach ($wp_posts as $i => $row){
$ID = $row['post_id'];
$title = $row['post_title'];
$content = $row['post_content'];
$postdate = $row['post_date']. " 12:00:00";
$imagePath = $row['post_imagePath'];
if (!get_page_by_title($title, 'OBJECT', 'post') ){
$my_post = array(
'ID' => $ID,
'post_title' => $title,
'post_content' => $content,
'post_date' => $postdate,
);
wp_insert_post( $my_post );
/* wp_insert_attachment */
$filetype = wp_check_filetype( basename( $imagePath ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $imagePath ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $imagePath ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $imagePath, $parent_post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
/* ./wp_insert_attachment */
}
}
Do not add the ID when using wp_insert_post(), this will try and update an entry with that ID.
IMPORTANT: Setting a value for $post['ID'] WILL NOT create a post with
that ID number. Setting this value will cause the function to update
the post with that ID number with the other values specified in $post.
In short, to insert a new post, $post['ID'] must be blank or not set
at all.
wp_insert_post() documentation
Also make sure the post has actually been inserted before continuing your script. eg
$post_id = wp_insert_post( $my_post );
if(!$post_id) {
//log an error or something...
continue;
}
Haven't test it but i think this will do it.
foreach ($wp_posts as $i => $row){
$ID = $row['post_id'];
$title = $row['post_title'];
$content = $row['post_content'];
$postdate = $row['post_date']. " 12:00:00";
$imagePath = $row['post_imagePath'];
$my_post = array(
'ID' => $ID,
'post_title' => $title,
'post_content' => $content,
'post_date' => $postdate,
);
$parent_post_id = wp_insert_post( $my_post ); //Returns the post ID on success.
/**** wp_insert_attachment ****/
$filetype = wp_check_filetype( basename( $imagePath ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name(basename($image_url)),
'post_content' => '',
'post_status' => 'inherit'
);
// So here we attach image to its parent's post ID from above
$attach_id = wp_insert_attachment( $attachment, $imagePath, $parent_post_id);
// Attachment has its ID too "$attach_id"
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
$res1= wp_update_attachment_metadata( $attach_id, $attach_data );
$res2= set_post_thumbnail( $parent_post_id, $attach_id );
}

Set featured image using wp_insert_post

// Auto post ( Unique File Date ).
$postData = array(
'post_category' => array( $Category ),
'post_status' => $Post_Status,
'post_type' => $Post_Type
);
$post_id = wp_insert_post( $postData );
$getImageFile = 'http://localhost/Multisite/test2/wp-content/uploads/sites/4/Auto Post/twitter.png';
$attach_id = wp_insert_attachment( $postData, $getImageFile, $post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $getImageFile );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
The code above make a post successfully but it is not setting the post featured image. I don't know what I am doing wrong here.
Use different $postData for the attachment:
$wp_filetype = wp_check_filetype( $getImageFile, null );
$attachment_data = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $getImageFile ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment_data, $getImageFile, $post_id );
Currently you're passing the identical post data to the post and its attachment post.
I use the function wp_upload_bits is new WordPress function for easy for uploading image. On the second line of my code $post is your $post_id id and for upload file directory I create custom folder that is custom-uploads for your better understanding or you can remove that on my 4th line of coding that is './'. 'custom-uploads' . '/'
$upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
$post_id = $posts; //set post id to which you need to set post thumbnail
$filename = $upload['file'];
$uploadfile = $uploaddir['basedir'] . '/'. 'custom-uploads' . '/';
move_uploaded_file($filename, $uploadfile); // (file name , designation)
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $posts );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id ); // set post thumnail (featured image) for the given post

wordpress form processing to custom post type not working

I'm trying to insert a custom post type for a multiple image upload form. The below code is the form processing. The page is blank when i submit the form. Where did i go wrong?
$art_title = $_POST['art_title'];
$i = 0;
foreach($art_title as $value) {
$art_title = $_POST['art_title'][$i];
$art_width = $_POST['art_width'][$i];
$art_height = $_POST['art_height'][$i];
$art_price = $_POST['art_price'][$i];
$art_creation_date = $_POST['art_creation_date'][$i];
$art_upload = $_FILES['art_upload'][$i];
$_SESSION['saved_art_form']['art_title'][$i] = $art_title;
$_SESSION['saved_art_form']['art_width'][$i] = $art_width;
$_SESSION['saved_art_form']['art_height'][$i] = $art_height;
$_SESSION['saved_art_form']['art_price'][$i] = $art_price;
$_SESSION['saved_art_form']['art_creation_date'][$i] = $art_creation_date;
$post = array(
'post_content' => '', // The full text of the post.
'post_name' => $art_title, // The name (slug) for your post
'post_title' => $art_title, // The title of your post.
'post_status' => 'draft', // Default 'draft'.
'post_type' => 'products', // Default 'post'.
'post_author' => '', // The user ID number of the author. Default is the current user ID.
'menu_order' => '0', // If new post is a page, sets the order in which it should appear in supported menus. Default 0.
'post_password' => '', // Password for post, if any. Default empty string.
'post_excerpt' => '', // For all your post excerpt needs.
'comment_status' => 'open' , // Default is the option 'default_comment_status', or 'closed'.
'post_category' => '' // Default empty.
);
$post_id = wp_insert_post( $post);
wp_set_post_categories( $post_id);
add_post_meta($post_id, '_width', $art_width, true);
add_post_meta($post_id, '_height', $art_height, true);
$filename = $_FILES["art_upload"][[$i]["name"];
$uploads = wp_upload_dir();
//file_put_contents($file, $image_data);
$file_array = array(
'name' => $_FILES['art_upload'][$i]['name'],
'type' => $_FILES['art_upload'][$i]['type'],
'tmp_name' => $_FILES['art_upload'][$i]['tmp_name'],
'error' => $_FILES['art_upload'][$i]['error'],
'size' => $_FILES['art_upload'][$i]['size']
);
// required for wp_handle_upload() to upload the file
$upload_overrides = array( 'test_form' => FALSE );
if ( !empty( $file_array['name'] ) ) {
// upload the file to the server
$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );
// checks the file type and stores in in a variable
$wp_filetype = wp_check_filetype( basename( $uploaded_file['art_upload'] ), null );
// set up the array of arguments for "wp_insert_post();"
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/.[^.]+$/', '', basename( $uploaded_file['art_upload'] ) ),
'post_content' => '',
'post_author' => '',
'post_status' => 'inherit',
'post_type' => 'attachment',
'guid' => $uploads['url'] . '/' . $file_array['name']
);
// insert the attachment post type and get the ID
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded_file['art_upload'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
// update the attachment metadata
wp_update_attachment_metadata( $attach_id, $attach_data );
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
set_post_thumbnail( $post_id, $post_thumbnail_id );
}
$i++;
}

wordpress create post from image upload

I have some code to create posts from uploading images into the media library, which is working fine:
add_action('add_attachment', 'create_post');
function create_post( $attach_ID ) {
$attachment = get_post( $attach_ID );
$my_post_data = array(
'post_title' => $attachment->post_title,
'post_type' => 'post',
'post_category' => array('0'),
'post_status' => 'publish'
);
$post_id = wp_insert_post( $my_post_data );
// attach media to post
wp_update_post( array(
'ID' => $attach_ID,
'post_parent' => $post_id,
) );
set_post_thumbnail( $post_id, $attach_ID );
return $attach_ID;
}
The catch is that I don't want it to create new posts from an image upload if I'm manually creating a post. In other words, I want the code to create new posts only if I upload images directly into the media library, not when I added images manually into a new post.
Any help is greatly appreciated!
Maybe there is a better way, but you could use the global variable $pagenow.
global $pagenow;
if($pagenow == 'upload.php'){
//your code here
}
I got some help from a developer on Wizpert. He used the below code to make it work
add_action('add_attachment', 'create_post');
function create_post( $attach_ID ) {
$attachment = get_post( $attach_ID );
if(!$attachment->post_parent)
{
$my_post_data = array(
'post_title' => $attachment->post_title,
'post_type' => 'post',
'post_category' => array('0'),
'post_status' => 'publish'
);
$post_id = wp_insert_post( $my_post_data );
// attach media to post
wp_update_post( array(
'ID' => $attach_ID,
'post_parent' => $post_id,
) );
set_post_thumbnail( $post_id, $attach_ID );
return $attach_ID;
}
}

Wordpress - Programmatically adding products not generating thumbnails

I'm creating a custom CSV importer for a client and the pictures are added, however the thumbnails aren't being generated properly. After using a plugin like Regenerate Thumbnails they do show correctly.
Here is the code in which I add the attachment and link it to the post.
$uploadDir = 'wp-content/uploads/importedproductimages/';
$siteurl = get_option('siteurl');
$thumbnail = 'importedproductimages/' . $name;
$filename = 'importedproductimages/' . $name;
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_author' => 1,
'post_date' => current_time('mysql'),
'post_date_gmt' => current_time('mysql'),
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_content' => '',
'post_status' => 'inherit',
'post_modified' => current_time('mysql'),
'post_modified_gmt' => current_time('mysql'),
'post_parent' => $post_id,
'post_type' => 'attachment',
'guid' => $siteurl.'/'.$uploadDir.$name
);
$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $thumbnail );
wp_update_attachment_metadata( $attach_id, $attach_data );
// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id);
Why aren't the thumbnails being generated properly?
Thank you in advance.
EDIT:
I have also included image.php like so:
require_once(ABSPATH . 'wp-admin/includes/image.php');
This ended up working for me:
function createnewproduct($product)
{
$new_post = array(
'post_title' => $product['Product'],
'post_content' => $product['Long_description'],
'post_status' => 'publish',
'post_type' => 'product'
);
$skuu = $product['SKU'];
$post_id = wp_insert_post($new_post);
update_post_meta($post_id, '_sku', $skuu );
update_post_meta( $post_id, '_regular_price', $product['ourPrice'] );
update_post_meta( $post_id, '_manage_stock', true );
update_post_meta( $post_id, '_stock', $product['Qty'] );
update_post_meta( $post_id, '_weight', $product['Weight'] );
if (((int)$product['Qty']) > 0) {
update_post_meta( $post_id, '_stock_status', 'instock');
}
$dir = dirname(__FILE__);
$imageFolder = $dir.'/../import/';
$imageFile = $product['ID'].'.jpg';
$imageFull = $imageFolder.$imageFile;
// only need these if performing outside of admin environment
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// example image
$image = 'http://localhost/wordpress/wp-content/import/'.$product['ID'].'.jpg';
// magic sideload image returns an HTML image, not an ID
$media = media_sideload_image($image, $post_id);
// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
);
// reference new image to set as featured
$attachments = get_posts($args);
if(isset($attachments) && is_array($attachments)){
foreach($attachments as $attachment){
// grab source of full size images (so no 300x150 nonsense in path)
$image = wp_get_attachment_image_src($attachment->ID, 'full');
// determine if in the $media image we created, the string of the URL exists
if(strpos($media, $image[0]) !== false){
// if so, we found our image. set it as thumbnail
set_post_thumbnail($post_id, $attachment->ID);
// only want one image
break;
}
}
}
}
}
Old question I know, but this came up on Google in my searches for the answer, and there is a better way to generate the thumbnails, as well as any other image sizes needed: wp_generate_attachment_meta. Used in two lines:
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
This refreshes ALL image sizes, including Thumbnails, when given an attachment ID.

Categories