How to get data in for loop - php

I run a for loop but it fetch only 22 page data as there is near about 800 data.
Any wordpress developer can check this what is wrong in this code that I would not able to get data of all page thanks in advance. If you feel my code is not clear please ask me for understanding.
$arr = array();
$counter = 1;
for($i=0;$i<1450;$i+=50)
{
$i;
$page = "http://www.cardkingdom.com/catalog/view?page=".$counter++."";
$all_page = file_get_contents($page);
preg_match_all
('/http:\/\/www.cardkingdom.com\/catalog\/item\/([0-9]+)/', $all_page,$match2);
$arr[] = $match2[0];
}
$arrs = count($arr);
for($i=0;$i<$arrs;$i++)
{
echo "Page no: ".$i;
for($j=0;$j<50;$j++){
echo '<div class="container">';
// get product detail on url basis
$input = file_get_contents($arr[$i][$j]);
preg_match('/http:\/\/www.cardkingdom.com\/\/product_images
\/(\d+)\/(\d+)\/(\d+)\/(\d)\/(\d+)\/(\d+)\/([0-
9_]+)standard(\.\w+)|http:\/\/www.cardkingdom.com\/media\/images\/products
\/standard\/([0-9]+[_]+[0-
9]+).jpg|http:\/\/www.cardkingdom.com\/media\/images\/products\/max\/([0-9]+
[_]+[0-9]+).jpg/', $input , $proimg);
// for print itmes
if(isset($proimg[0])){
echo $postGuid = $proimg[0]; echo "<br>";
}
// End
// get products title,description
preg_match
('/<td valign=.*?>\s+?<b>(.*?)<br><span style=.*?>(.*?)<\/span><\/b><br><br>\s+? (.*?|.*+\n+.*?)<BR>|<td valign=.*? width=.*?>\s+?<b>(.*?)<\/b>\s+?<br>\s+?<a href="(.*?)">(.*?)<\/a>\s+<br><br>\s+?(.*?<br>.*?<br>|.*?<br>.*?<BR>\s+.*?<br>)|<td valign=.*? width=.*?>\s+?<b>(.*?)<\/b>\s+?<br>\s+?<a href="(.*?)">(.*?)<\/a>\s*<br><br>\s+?(.*?<br>.*?<BR>\s+?.*?<BR>)|<td valign=.*?>\s+?<b>(.*?)<br><span style=.*?>(.*?)<\/span><\/b><br><br>\s+?([a-zA-z\s\.\'\<\br\>\a-z0-9\<\br\>]*)<\/span>/',$input , $match_title);
//echo "<pre>";
if((isset($match_title[1])) && ($match_title[1]!='')) {
echo $posTitle = htmlspecialchars($match_title[1]); echo "<br>";
}
if((isset($match_title[12])) && ($match_title[12]!='')){
echo $posTitle = htmlspecialchars($match_title[12]); echo "<br>";
}
if((isset($match_title[2])) && ($match_title[2]!='')) {
echo $postContent = $match_title[2]; echo "<br>";
}
if((isset($match_title[3])) && ($match_title[3]!='')) {
echo $postContent = $match_title[3]; echo "<br>";
}
if((isset($match_title[4])) && ($match_title[4]!='')) {
echo $posTitle = $match_title[4]; echo "<br>";
}
if((isset($match_title[8])) && ($match_title[8]!='')) {
echo $posTitle = $match_title[8]; echo "<br>";
}
if((isset($match_title[5])) && ($match_title[5]!='')) {
echo $postContent = $match_title[5];"<br>";
}
if((isset($match_title[6])) && ($match_title[6]!='')) {
echo $postContent = $match_title[6]; echo "<br>";
}
if((isset($match_title[7])) && ($match_title[7]!='')) {
echo $postContent = $match_title[7]; echo "<br>";
}
if((isset($match_title[9])) && ($match_title[9]!='')) {
echo $postContent = $match_title[9]; echo "<br>";
}
if((isset($match_title[10])) && ($match_title[10]!='')){
echo $postContent = $match_title[10]; echo "<br>";
}
if((isset($match_title[11])) && ($match_title[11]!='')){
echo $postContent = $match_title[11]; echo "<br>";
}
if((isset($match_title[13])) && ($match_title[13]!='')){
echo $postContent = $match_title[13]; echo "<br>";
}
if((isset($match_title[9])) && ($match_title[9]!='')) {
echo $postContent = $match_title[9]; echo "<br>";
}
if((isset($match_title[14])) && ($match_title[14]!='')){
echo $postContent = $match_title[14]; echo "<br>";
}
//$match_arr[] = $match_title[0];
// price of products
preg_match('/<br><br><span style=.*?>(.*?)<\/span><br><br>\s+?Price:(\s*\$(\d+\.\d+))\s+?<br><br>/' , $input ,$match_price);
//echo "<pre>";
if(isset($match_price[3])){
echo $productprice =$match_price[3]; echo "<br>";
}
// stock of products
preg_match('/<i>\(([0-9]+)/' , $input, $stock );
//echo "<pre>";
if(isset($stock[1])){
echo $availstock = $stock[1];echo "<br>";
}
echo "<br><br>";
// database query to insert products in woocommerce
$prefix = $wpdb->prefix;
$seLastPosts = "SELECT max(ID) as maxid FROM ".$prefix."posts";
$getLastId = $wpdb->get_results($seLastPosts);
/* $lastIdposts = $getLastId[0]->maxid; NOTE : Last ID of wp_posts */
// check if record exsist is databse and update database
$resCheck = $wpdb->get_results(
"SELECT COUNT(*) AS counter FROM ".$prefix."posts
WHERE post_title='".mysql_real_escape_string($posTitle)."'");
echo $count = $resCheck[0]->counter;
// result check for guid
$resCheck_guid = $wpdb->get_results("SELECT guid FROM ".$prefix."posts
WHERE guid='".mysql_real_escape_string($proimg[0])."'");
$guid_noduplacate = $resCheck_guid[0]->guid;
//echo $count = $resCheck[0]->guid;
// count product if > 0 then record is not inserted into database
// insert query in databse
if($count > 0 ){
// set update query if record exist in table
$update = $wpdb->update(
$prefix."posts",array("post_content" => $postContent,
"post_status" => "publish",
"post_type" => "product"),array("post_title" => $posTitle));
$select = $wpdb->get_results(
"SELECT ID AS productsId FROM ".$prefix."posts
WHERE post_title='".$posTitle."'");
$updateImg = $wpdb->update($prefix."posts",array("guid" => $postGuid),
array("post_parent" => $select[0]->productsId ));
$postmetaIns = $wpdb->Update($prefix."postmeta",array("
meta_value" => $productprice),array("
post_id" => $select[0]->productsId,"meta_key" => "_price"));
$postmetaIns2 = $wpdb->update($prefix."postmeta",array(
"meta_value" => $availstock),array("post_id" => $select[0]->productsId,
"meta_key" => "_stock"));
//$img = ABSPATH.'wp-content/uploads/2014/07/'.$proimg[7].'standard'.$proimg[8];
///file_put_contents($img,$input);
// 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($proimg[0]);
// Get image data
$filename = basename($proimg[0]); // 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 ); */
// End here
}
if($count <1)
{
// if record not exist insert New record
/*$insert = $wpdb->insert( $prefix."posts", array("post_title" => $posTitle,
"post_content" => $postContent,
"post_status" => "publish","post_type" =>"product")); */
// Register Post Data
$post = array();
$post['post_status'] = 'publish';
$post['post_type'] = 'product'; // can be a CPT too
$post['post_title'] = mysql_real_escape_string($posTitle);
$post['post_content'] = $postContent;
$post['post_author'] = 1;
// Create Post
$post_id = wp_insert_post( $post );
// select products ID
$select = $wpdb->get_results("SELECT ID AS productsId FROM ".$prefix."posts
WHERE post_title='".$posTitle."'");
//echo $select[0]->productsId; die();
// insert Image in pots and product attribute meta posts table
//$insertImg = $wpdb->insert($prefix."posts",array("post_status" =>"inherit",
"post_type" => "attachment",
"guid" => $postGuid,"post_parent" => $select[0]->productsId ));
$select[0]->productsId;
// Add Featured Image to Post
$image_url = $proimg[0]; // Define the image URL here
$upload_dir = wp_upload_dir(); // Set upload folde r
$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 da ta
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
if(!$guid_noduplacate){
$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 );
add_post_meta( $post_id, '_thumbnail_id', $attach_id, true );
add_post_meta( $post_id, '_price', $productprice, true );
add_post_meta( $post_id, '_stock', $availstock, true );
// End here
/* $imgId = $wpdb->get_results("SELECT ID AS imageId FROM ".$prefix."posts
WHERE post_parent=".$select[0]->productsId."");
//echo "hello".$imgId[0]->imageId;
// Entry INTO postmeta table of products attribute
// price,stock and _thumbnail_id
$postmetaIns = $wpdb->insert($prefix."postmeta",array(
"post_id" => $select[0]->productsId,
"meta_key" => "_thumbnail_id","meta_value" => $imgId[0]->imageId));
$postmetaIns = $wpdb->insert($prefix."postmeta",array("
post_id" => $select[0]- >productsId,"meta_key" => "_price",
"meta_value" => $productprice));
$postmetaIns = $wpdb->insert($prefix."postmeta",array(
"post_id" => $select[0]->productsId,"meta_key" => "_stock",
"meta_value" => $availstock)); */
}
echo "</div>";
}
}

this is how i would do it, in your initial for loop you increment counter but it will never reach more than 29 because 1450 / 50 (the value you increment your for loop) = 29, your counter reaches max value 29 so you will only get 29 pages to file_get_contents from. for the preg match, i am unsure what you want to achieve from it as i do not have a sample of the page, but you will definitely have ALL the results in $match2 (i don't think this is something you would want). my advice is to debug your code slowly, aka add a var_dump for most of your vars inside each of your for loops and a quick exit/break so you know what kind of data you are actually looking at. it is common practice to escape the slashes but you could just as well use a different regexp separator like % or # so your code is more readable. hope this helps
$arr = array();
for($i=0;$i<1450;$i++)
{
$page = "http://www.cardkingdom.com/catalog/view?page=".$i;
$all_page = file_get_contents($page);
preg_match_all('%http://www.cardkingdom.com/catalog/item/([0-9]+)%ism', $all_page, $match2);
$arr[] = $match2[0];
}

Related

How would I redirect to a newly created post in WordPress on form submission?

I am building a plugin that allows users to make a post and then I want it to redirect to the newly created post when the user submits the form. The problem I am running in to is getting the permalink for the new blog post and passing it through to the init function.
function create_post(){
if(is_user_logged_in())
{
if(isset($_POST['ispost']))
{
global $current_user;
get_currentuserinfo();
$user_login = $current_user->user_login;
$user_email = $current_user->user_email;
$user_firstname = $current_user->user_firstname;
$user_lastname = $current_user->user_lastname;
$user_id = $current_user->ID;
$post_title = $_POST['title'];
$sample_image = $_FILES['sample_image']['name'];
$post_content = $_POST['sample_content'];
$category = $_POST['category'];
$new_post = array(
'post_title' => $post_title,
'post_content' =>$post_content,
'post_status' => 'publish',
'post_type' => $post_type,
'post_category' => $category
);
// echo do_shortcode('[wpstream_go_live id="12"]');
$pid = wp_insert_post($new_post);
add_post_meta($pid, 'meta_key', true);
if (!function_exists('wp_generate_attachment_metadata'))
{
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES)
{
foreach ($_FILES as $file => $array)
{
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK)
{
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $pid );
}
}
if ($attach_id > 0)
{
//and if you want to set that image as Post then use:
update_post_meta($pid, '_thumbnail_id', $attach_id);
}
$my_post1 = get_post($attach_id);
$my_post2 = get_post($pid);
$my_post = array_merge($my_post1, $my_post2);
}
}
else
{
echo "<h2 style='text-align:center;'>User must be login for add post!</h2>";
}
}
add_action('init', 'myInit');
function myInit() {
if (isset($_POST['ispost'])) {
$errors = myFormValidation();
if (empty($errors)) {
//Do whatever you want here
header('Location: ' . get_permalink());
}
//Set the errors here
}
}
The only thing that I can think of is using sessions to pass the permalink from one function to another. What would be the best way of getting and passing the permalink to the init function? Also when I exit after the header() it returns a blank page but if I don't it works.
You can redirect the user after processing the form by using JavaScript. Something like...
echo '<script type="text/javascript">';
echo 'window.location = "' . $url . '"';
echo '</script>';

Wordpress Auto Rename and Fill Attributes on upload to CPT

as you can see this code to rename images by post title works fine.
even with several posts with the same title.
it just puts the numbers: image, image1, image2, image3 .. etc
/*Renaming attachment files to the post title*/
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if ( get_post_type( $_REQUEST['post_id'] ) === 'property'){
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $filename;
}
}
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
/* Automatically set the image Title, Alt-Text, Caption & Description upon upload*/
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
if ($post_id != false) {
$my_image_title = get_the_title($post_id);
} else {
$my_image_title = get_post( $post_ID )->post_title;
}
// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$my_image_title = ucwords( strtolower( $my_image_title ) );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
'post_excerpt' => $my_image_title, // Set image Caption (Excerpt) to sanitized title
'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
I believe this code works since inside in CPT property he renames my upload to
post-title.jpg
result : post-title.jpg , post-title-1.jpg, post-title-2.jpg , post-title-3.jpg, etc....
and outside CPT property in wordpress he rename strange empty-1.jpg to uploads..
result : -1.jpg , -2.jpg , -3.jpg etc .....
I will need help to add some instructions
I must miss an instruction to tell him ,it should only fire in CPT property only
else --> do nothing if there is no title and if we are not in CPT property.
so he does not rename the uploads to 'auto-draft.jpg' when no title set and image uploaded first .. very annoying.. and if we are outside CPT'property' do nothing = leave the names of the original uploads and ignore this code.
I think simply commenting (or removing) these two lines in your file_renamer() function will do the trick:
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
Because if ( get_post_type( $_REQUEST['post_id'] ) === 'property'){ is the line that checks whether the post_id belong to a Custom Post Type. Based on what I understood from your explanation, you only want do the renaming there. If you want to do something else too, you could write inside that IF condition.
So your code would look like this:
/*Renaming attachment files to the post title*/
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if ( get_post_type( $_REQUEST['post_id'] ) === 'property'){
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
//$my_image_title = $post;
//$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $filename;
}
}
Btw, I didn't tested the code!

How to update or save multiple checkbox on update post meta in wordpress?

I can successfully create a post and also update or insert the data to the custom fields.
But i've no Idea how to update or check the multiselect checkboxes.
Below is the code for creating a post with featured image and inserting custom fields.
Please suggest me to add also the multiple select checboxes.
<?php
error_reporting(E_ALL);
#ini_set('display_errors', 1);
require('wp-load.php');
global $user_ID;
$title = $_REQUEST['title'];
$content = $_REQUEST['content'];
$status = $_REQUEST['status'];
$date = $_REQUEST['date'];
$type = $_REQUEST['type'];
$bedrooms = $_REQUEST['bedrooms'];
$bathrooms = $_REQUEST['bathrooms'];
$floor = $_REQUEST['floor'];
$sqft = $_REQUEST['sqft'];
$afterfee = $_REQUEST['afterfee'];
$sp = $_REQUEST['saleprice'];
echo $title;
echo $content;
echo $status;
echo $type;
echo $bedrooms;
echo $bathrooms;
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => $status,
'post_date' => $date,
'post_author' => $user_ID,
'post_type' => $type,
'post_category' => array(0)
);
$id = wp_insert_post($new_post);
update_post_meta($id,'fave_property_bedrooms',$bedrooms);
update_post_meta($id,'fave_property_bathrooms',$bathrooms);
update_post_meta($id,'fave_video_url','www.google.com');
update_post_meta($id,'fave_property_price_postfix',$afterfee);
update_post_meta($id,'fave_property_land_postfix',$sqft);
update_post_meta($id,'fave_property_land',$floor);
update_post_meta($id,'fave_property_price_prefix','Start From');
update_post_meta($id,'fave_property_price_postfix','Per Month');
update_post_meta($id,'fave_property_price',$sp);
$post_id=$id;
// 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 = 'https://clevertechie.com/img/main/php-curl-tutorial.png';
// 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;
}
}
}
}
?>

Add file from server wordpress plugin checking and limit of 999 files

I am using this wordpress plugin in order to add files from server and I have 2 issues. Files are not being skipped, therefore I needed to alter the code myself in order to add a checking process, but the problem is that the checking process is very slow for each file. Second issue is that the plugin can't add more than 999 files at once and I need to add about 50000 files to the media library.
Code that I altered to check if the file is in the media library and skip it:
class.add-from-server.php
function handle_imports() {
if ( !empty($_POST['files']) && !empty($_POST['cwd']) ) {
$query_images_args = array(
'post_name' => trim ( $post_name ), 'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1,
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$image_trim = wp_get_attachment_url( $image->ID );
$image_trim = explode('/', $image_trim);
$images[] = end($image_trim);
}
// $images is the array with the filenames where I stock the media library files
$files = array_map('stripslashes', $_POST['files']);
$cwd = trailingslashit(stripslashes($_POST['cwd']));
$post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
$import_date = isset($_REQUEST['import-date']) ? $_REQUEST['import-date'] : 'file';
$import_to_gallery = isset($_POST['gallery']) && 'on' == $_POST['gallery'];
if ( ! $import_to_gallery && !isset($_REQUEST['cwd']) )
$import_to_gallery = true; // cwd should always be set, if it's not, and neither is gallery, this must be the first page load.
if ( ! $import_to_gallery )
$post_id = 0;
flush();
wp_ob_end_flush_all();
foreach ( (array)$files as $file ) {
if (!in_array($file, $images)) {
// here I ask if the image that I want to add is in the media library or not
$filename = $cwd . $file;
$id = $this->handle_import_file($filename, $post_id, $import_date);
if ( is_wp_error($id) ) {
echo '<div class="updated error"><p>' . sprintf(__('<em>%s</em> was <strong>not</strong> imported due to an error: %s', 'add-from-server'), esc_html($file), $id->get_error_message() ) . '</p></div>';
} else {
//increment the gallery count
if ( $import_to_gallery )
echo "<script type='text/javascript'>jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);</script>";
echo '<div class="updated"><p>' . sprintf(__('<em>%s</em> has been added to Media library', 'add-from-server'), esc_html($file)) . '</p></div>';
}
flush();
wp_ob_end_flush_all();
} else {
echo '<div class="updated error">File '.$file.' had been skipped because it is already in the media library.</div>';
}
}
}
}
So please help
1. How can I speed up the checking process, want to mention that this code is the one that slowing down the process (true that I have 10000 images in the media library):
$query_images_args = array(
'post_name' => trim ( $post_name ), 'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1,
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$image_trim = wp_get_attachment_url( $image->ID );
$image_trim = explode('/', $image_trim);
$images[] = end($image_trim);
}
Second issue the one with the 999 files limit, how to overcome this limit? I believe is related to the wordpress code but don't know how to by pass it.
Okay, I'm not going to answer your question directly because I don't understand why you're using a plugin to do this but ... what you're trying to do is easy enough without the use of a plugin.
First, you need to loop a directory, then check if the media exists, and if not, add the media to the media library.
function thisismyurl_add_media_to_library() {
global $wpdb;
$file_count = 0;
/* if the user isn't an admin user, don't do anything */
if ( ! current_user_can( 'manage_options' ) )
return;
/* (you'll want to reset this to your path */
$file_path = ABSPATH . '/import/path/to/files/';
/* get a list of all files in a specific directory */
$files = glob( $file_path . '*.jpg');
if ( ! empty( $files ) ) {
/* now we loop the files */
foreach ( $files as $file ) {
unset( $post_id );
/* it's likely that a server will time out with too many files so we're going to limit it to 999 new files */
if ( $file_count < 999 ) {
$filename = str_replace( $file_path, '', $file );
/* check to see if the image already exists */
$post_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s", $filename ) );
/* the file does not exist */
if ( empty( $post_id ) ) {
/* only count new files when checking for the file count */
$file_count++;
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => wp_check_filetype( basename( $file ), null ),
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
wp_insert_attachment( $attachment, $filename );
/* this is commented out for now, but if you uncomment it, the code will delete each file after it's been inserted */
/*
if ( $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s", $filename ) ) )
unlink( $file );
*/
} /* if */
}
} /* foreach */
} /* if */
}
add_action( 'wp_head', 'thisismyurl_add_media_to_library' );

Why isn't implode adding string to array?

I have this section of code but for some reason the comma isn't being added to separate the array elements. What am I overlooking?
$imgid = array();
foreach ( $attachments as $attachment ) {
$imgid[] = $attachment->ID;
// echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
}
$string = implode(',', $imgid);
echo $string;
The above foreach code is located in a larger foreach statement:
foreach ($fileslist as $file) {
if( $file === '.' || $file === '..' ) {
continue;
}
$file = file_get_contents( $post_dir . "/" . $file);
$filetype = "image/jpeg";
$filename = "remote_filename_". $i .".jpg";
$i++;
xmlrpc_set_type($file,'base64'); // <-- required!
$params = array($blogid,$username,$password,
array('name'=>$filename,'type'=>$filetype,'bits'=>$file,'overwrite'=>false));
$request = xmlrpc_encode_request('wp.uploadFile',$params);
$result = go($request,$rpcurl);
print_r($result);
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_status' => null,
'post_mime_type' => 'image'
));
$imgid = array();
foreach ( $attachments as $attachment ) {
$imgid[] = $attachment->ID;
// echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
}
$comma_separated = implode(",", $imgid);
echo $comma_separated;
}
Basically, what this does is it takes each image in a directory and uploads it to WordPress. There is an attachment ID for each image and I am needing to get each attachment ID saved as a string with each ID separated by a comma.
Edit: Simon Robb provided the correct answer for me. Here is updated and final code:
foreach ($fileslist as $file) {
if( $file === '.' || $file === '..' ) {
continue;
}
$file = file_get_contents( $post_dir . "/" . $file);
$filetype = "image/jpeg";
$filename = "remote_filename_". $i .".jpg";
$i++;
xmlrpc_set_type($file,'base64'); // <-- required!
$params = array($blogid,$username,$password,
array('name'=>$filename,'type'=>$filetype,'bits'=>$file,'overwrite'=>false));
$request = xmlrpc_encode_request('wp.uploadFile',$params);
$result = go($request,$rpcurl);
print_r($result);
$attachments = get_posts( array(
'post_type' => 'attachment',
// 'posts_per_page' => 1,
'post_status' => null,
'post_mime_type' => 'image'
));
$imgid = array();
foreach ( $attachments as $attachment ) {
$imgid[] = $attachment->ID;
// echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
}
echo "<br />";
$comma_separated = implode(",", $imgid);
}
echo $comma_separated;
I'm not 100% clear on how your code is intended to work, but currently each $file in your $filelists loop is only returning one attachment, because of the 'posts_per_page' => 1 parameter in get_posts. Therefore the $imgid variable only ever has one element, so implode doesn't have two element to put the comma between.
The output you're seeing is actually one ID being outputted for each loop of $filelist.
If you remove the 'posts_per_page' => 1 parameter, you'll have the full array of attachments in $attachments and it should work fine.
Your logic is sound & should work as expected. But without seeing your larger codebase it is hard to tell what is happening. My only guess is there is a larger loop in play & your initing of $imgid is reseting the array each iteration:
$imgid = array();
Is it possible for you to place that array init higher up in your logic? If so, try that to see what happens. And maybe assiging the index key with the $attachment->ID would help:
$imgid = array();
foreach ( $attachments as $attachment ) {
$imgid[$attachment->ID] = $attachment->ID;
// echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
}

Categories