How to add Woocommerce Product Gallery using Gravity Forms - php

I am trying to add WooCommerce Product Gallery using Gravity forms multiple file upload but product gallery should not be added
add_action( 'gform_after_submission_3', 'set_post_content', 10, 2 );
function set_post_content( $entry, $form ) {
if (!function_exists('wp_generate_attachment_metadata')) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
}
$uploaded_files = json_decode(rgpost("gform_uploaded_files"));
foreach($uploaded_files->input_76 as $key => $data){
if (isset($_FILES[$data])) {
$file_url = $data->input_76; //great but what is its url?
$upload_dir = wp_upload_dir(); //where do you want to put it?
$file_data = file_get_contents($file_url); //show me what you're made of
$filename = basename($file_url); //so cute but what's its name?
if (wp_mkdir_p($upload_dir['path'])) //can we put it there?
$file = $upload_dir['path'] . '/' . $filename; //yes great
else //or no, okay fine let's try somewhere else
$file = $upload_dir['basedir'] . '/' . $filename; //get the whole location
file_put_contents($file, $file_data); // tada home at last
//$wp_filetype = wp_check_filetype($filename, array('pdf' => 'application/pdf','pdf' => 'application/x-pdf') ); //is it the right type of of file?
$attachment = array(//set up the attachment
//'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file, $entry['post_id']); //insert attachment
$attach_data = wp_generate_attachment_metadata($attach_id, $file); //asign the meta
wp_update_attachment_metadata($attach_id, $attach_data); //update the post
update_post_meta($entry['post_id'], '_product_image_gallery', $attach_id);
}
}
}

Related

Upload time of posts posted using php in Wordpress increasing

We are uploading custom posts to our wordpress site using the code below. Basically the posts are a folder containing 10-15 image files which are being recursively retrieved from the C:/******/S1/ folder. A post is created using the name of the folder and the contents, being image files are created as attachment types and associated with that particular post. We are using the groups plugin to handle access control.
The problem is when we first started using this code we could upload 100 custom types in 14-15 mins. But the time is consistently increasing and now it takes around 30-35 mins for the same number of posts, the size and number remaining the same. We are not sure how long this time will reach as we continue to upload posts, we intend to create around 30000 posts over a period of a month. Hence the time is a critical factor. We have uploaded around 3000 till now.
We are not sure why this time period is increasing and we need to keep it constant. We have currently hosted this application on a 4 GB RAM, 2.6Ghz 2 core processor system. Currently posts table has around 53000 entries and post_meta has around 70000 entries. Any suggestions/advice are most welcome!!
Thanks in advance!!
function upload_service_register_call_func2() {
echo "<form id=\"featured_upload\" method=\"post\" action =\"/wordpress/index.php/upload-sr-status-v2/\" />";
echo "<input type=\"text\" name=\"my_image_upload\" value=\"C:/******/S1/\" id=\"my_image_upload\" />";
echo"<input id=\"submit_my_image_upload\" name=\"submit_my_image_upload\" type=\"submit\" value=\"Upload\" />";
echo"</form>";
}
function upload_service_register_func2() {
$filename = $_POST[my_image_upload];
$results = array();
$directory1 = $filename;
$handler1 = opendir($directory1);
$uploads_dir=wp_upload_dir();
// open directory and walk through the filenames
while ($file1 = readdir($handler1)) {
if ($file1 != "." && $file1 != "..") {
$directory = $filename."/".$file1;
$handler = opendir($directory);
$myproducts = get_posts( array(
'post_type' => 'se******rs',
'meta_query' => array(
array(
'key' => 's*******o',
'value' => $file1
)
)
) );
$uploaddir = wp_upload_dir();
if (file_exists($uploaddir['path'] . '/'. 'ST' . '/' . $file1)) {
delete_directory($uploaddir['path'] . '/'. 'ST' . '/' . $file1);
}
if(!empty($myproducts)){
foreach($myproducts as $myproduct)
{
wp_delete_post( $myproduct->ID, true);
}
}
$post["id"] = wp_insert_post( array(
"post_title" => $file1,
"post_content" => "",
"post_type" => "se******rs",
"post_status" => "publish",
'meta_query' => array(
array(
'key' => 's*******o',
'value' => $file1
)
)));
$content="";
$files = array();
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
array_push($files,$file);
}
}
natsort($files);
$count=0;
foreach($files as $file)
{
$date = date_create();
$timestamp = date_timestamp_get($date);
$foldercreate = wp_mkdir_p($uploaddir['path'] . '/'. 'ST' . '/' . $file1);
$uploadfile = $uploaddir['path'] . '/'. 'ST' . '/' . $file1. '/' .$timestamp $file;
$contents= file_get_contents($directory."/".$file);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
if($count==0)
{
copy('C:\********************\uploads\STORE\index.html',$uploaddir['path'] . '/'. 'ST' . '/' . $file1 . '/index.html' );
copy('C:\********************\uploads\STORE\.htaccess',$uploaddir['path'] . '/'. 'ST' . '/' . $file1 . '/.htaccess');
}
$count++;
$parent_post_id = $post["id"];
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $file ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] .'/'. 'ST'. '/' . $file1. '/' . basename( $uploadfile ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $uploadfile, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
$image = $wp_upload_dir['url'] .'/'. 'ST'. '/' . $file1. '/' . basename( $uploadfile );
$content = $content."<img style=\"width:150px;height:150px\"; class=\"alignleft size-thumbnail wp-image-".$attach_id."\" src=\"".$image."\" />";
}
$content=$content."";
$my_post = array(
'ID' => $post["id"],
'post_content' => $content,
);
wp_update_post($my_post);
$group_id=get_group_id_by_name( $file1 );
if(!$group_id) $group_id=4;
add_post_meta($post["id"],"groups-read",$group_id);
add_post_meta($post["id"],"groups-read","2");
add_post_meta($post["id"],"s******o",$file1);
$em***=$file1;
$sql2="SELECT de**,bi******* FROM b**********8 WHERE em*** = %s";
$results2=prdt_run_sql($sql2,$em***);
if($results2)
{
foreach($results2 as $data)
{
$de**='SR_'.$data->de**;
$bi******='SR_'.$data->bi*******;
break;
}
$group_id=get_group_id_by_name($de**);
add_post_meta($post["id"],"groups-read",$group_id);
$group_id=get_group_id_by_name($bi*****);
add_post_meta($post["id"],"groups-read",$group_id);
echo "Uploaded folder ".$file1." with permissions<br/>";
}
else
{
echo "Uploaded folder ".$file1." without permissions<br/>";
}
}
}
echo"Completed Uploading folders <br/>";
}

Generating Wordpress featured image in foreach loop, showing same image for multiple posts

Good evening. I've written a function to programmatically insert a Wordpress post for each of our YouTube videos, using a foreach loop.
Everything is working wonderfully, until I get to inserting the post thumbnail. I am using a function that automatically handles the uploading and inserting of a thumbnail, and associating it with a post (below):
function Generate_Featured_Image($image_url, $post_id) {
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($post_id.'-'.$image_url);
if (wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename;
else $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);
$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, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
$res1 = wp_update_attachment_metadata( $attach_id, $attach_data );
$res2 = set_post_thumbnail( $post_id, $attach_id );
}
This function does work, but for some odd reason, it only uploads the image from the last video in the loop. For example, if I have 5 videos, 5 posts will be created. Each containing it's own specific information, but the post thumbnail will all be the image from the last (5th) video. None of them have their own thumbnail.
Here's a slimmed down verson of my function that creates the posts:
function createYouTubePost() {
...some other code...
$JSON = file_get_contents('https://www.googleapis.com/youtube/v3/search?order='.$api_order.'&part='.$api_part.'&channelId='.$channel_id.'&maxResults='.$max_results.'&key='.$api_key);
$json_data = json_decode($JSON, true);
foreach ($json_data['items'] as $data) {
$video_id = $data['id']['videoId'];
$video_title = $data['snippet']['title'];
$video_description = $data['snippet']['description'];
$video_thumb_url = $data['snippet']['thumbnails']['high']['url'];
$video_thumb_width = $data['snippet']['thumbnails']['high']['width'];
$video_thumb_height = $data['snippet']['thumbnails']['high']['height'];
$video_publish_date = $data['snippet']['publishedAt'];
$args = array(
'post_title' => substr($video_title, 0, strrpos($video_title, '(')),
'post_content' => $video_description,
'post_status' => 'publish',
'post_type' => 'download',
);
if (!if_download_exists(substr($video_title, 0, strrpos($video_title, '(')))) {
$new_post_id = wp_insert_post($args, true);
if ($new_post_id == 0) {
echo '<br>Could not create the post.';
var_dump($new_post_id);
}
else {
Generate_Featured_Image($video_thumb_url, $new_post_id);
...lots of code to update various post_meta fields...
echo '<br>New post created.<br>';
var_dump($new_post_id);
}
}
}
}
Here you can see the media attachments and how they're all the same:
And here are the individual posts that were created:
As you can see, each image is assigned to it's respective post, but the image is the same.
I have even tried setting the filename of each picture with a unique ID so that they're all different, but that didnt help. I have also confirmed that the image url's that I am passing to the function are all different.
My question is, if I am using my function Generate_Featured_Image() in a foreach loop, and provding it with unique information, why is it only using the last picture in the loop?
Thanks for any help!
I went with another solution. Wordpress' media_sideload_image() function works and is a more straight forward solution for my situation.
Here is the function that I'm now using to assign a thumbnail to a post:
function generateFeaturedImage($image_url, $post_id) {
// required libraries for media_sideload_image
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// $post_id == the post you want the image to be attached to
// $video_thumb_url == the vimeo video's thumb url
// $description == optional description
// load the image
$result = media_sideload_image($image_url, $post_id);
// then find the last image added to the post attachments
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if (sizeof($attachments) > 0) {
// set image as the post thumbnail
set_post_thumbnail($post_id, $attachments[0]->ID);
}
}
Here's the link to the stack exchange solution that I found.

How do I link to external images in my WP posts

I am scraping a site and putting data in my WP site.
There are lots of images in those posts.
I want that when importing that scraped data into my WP site,
I want to link images into my site directly from that external URL instead of downloading image to my server.
I am grammatically importing scraped data to my site.
Here is that part of adding image
// for image
$ins_q = "INSERT INTO wpxw_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, "
. "comment_status, ping_status,"
. "post_password, post_name, to_ping, pinged, post_modified,post_modified_gmt, post_content_filtered,post_parent,"
. "guid,menu_order,post_type,"
. "post_mime_type,comment_count) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$sth = $conn->prepare($ins_q);
if (!$sth->execute(array(
$post_author, $date, $date, "", sanitize_title_with_dashes($image_name), "", "inherit", "open", "closed", '',
str_replace(".", "-", $image_name), '', '', $date, $date, '', $post_id,
"http://photos2.zillowstatic.com/p_f/ISdc6hruhctopo0000000000.jpg"
, 0, "attachment", "image/jpeg", 0
))) {
echo "<h1>Error</h1>";
print_r($sth->errorInfo());
exit();
}
}
MY PROBLEM is that when adding external link to image, images do not show on my post. How can I show images from external resources?
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

How to differ two uploads in one form with same upload handling?

I have already created a form for my plugin, and it has two upload fields; one for an image and one for a zip-file. They are both using the same upload handler, and I want to save the attachment ID's to the database. The problem is that they use the same upload handler, so the value of the variable with the attachment ID will always be the last upload field. How is the best way to do this? Save in array (first index is first field, second index is second field)? Two upload handler is probably a bit overkill. Any ideas how to solve this in a good way?
This is the function that handles the upload:
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
}
As I said, as both upload fields uses the same function, the $attach_ID variable will be the value of the latest upload.
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
// $ids[]= $attach_id;
// save $attach id here, its correct for this loop, on the next loop it will be different and so on..
}
}
return $ids; // or save here serialize() maybe needed depending on how you are saving.
}

WordPress file "upload" from plugin

I'm trying to create plugin importing posts to WordPress. Imported articles (XML) contain "image-name" attribute and this image is already uploaded to the server.
I would like to, however, make WordPress do its "magic" and import the image to the system (create thumbnails, attach it to the post, place it under the wp-uploads directory scheme)... I found function media_handle_upload($file_id, $post_id, $post_data, $overrides) but it requires array $_FILES to be filled with actual upload (and I'm not uploading file - it is already placed on the server) so it's not very useful
Do you have any hint how to proceed?
Thanks
Check the following script to get the idea. (It does work.)
$title = 'Title for the image';
$post_id = YOUR_POST_ID_HERE; // get it from return value of wp_insert_post
$image = $this->cache_image($YOUR_IMAGE_URL);
if($image) {
$attachment = array(
'guid' => $image['full_path'],
'post_type' => 'attachment',
'post_title' => $title,
'post_content' => '',
'post_parent' => $post_id,
'post_status' => 'publish',
'post_mime_type' => $image['type'],
'post_author' => 1
);
// Attach the image to post
$attach_id = wp_insert_attachment( $attachment, $image['full_path'], $post_id );
// update metadata
if ( !is_wp_error($attach_id) )
{
/** Admin Image API for metadata updating */
require_once(ABSPATH . '/wp-admin/includes/image.php');
wp_update_attachment_metadata
( $attach_id, wp_generate_attachment_metadata
( $attach_id, $image['full_path'] ) );
}
}
function cache_image($url) {
$contents = #file_get_contents($url);
$filename = basename($url);
$dir = wp_upload_dir();
$cache_path = $dir['path'];
$cache_url = $dir['url'];
$image['path'] = $cache_path;
$image['url'] = $cache_url;
$new_filename = wp_unique_filename( $cache_path, $filename );
if(is_writable($cache_path) && $contents)
{
file_put_contents($cache_path . '/' . $new_filename, $contents);
$image['type'] = $this->mime_type($cache_path . '/' . $new_filename); //where is function mime_type() ???
$image['filename'] = $new_filename;
$image['full_path'] = $cache_path . '/' . $new_filename;
$image['full_url'] = $cache_url . '/' . $new_filename;
return $image;
}
return false;
}

Categories