Wordpress Auto Rename and Fill Attributes on upload to CPT - php

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!

Related

Wordpress rename uploaded images based on the post_title

I'm looking for a way to tell wordpress to rename the images attached to the post, by the name of the post.
I found this plugin to do the trick but.. it's stupid to use a plugin for such a simple function. . So I found this code in this article
/* 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 ) ) {
$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 );
}
}
and another one here
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
get_currentuserinfo();
return $current_user->user_login . $ext;
}
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
both work but how do you combine them into one code?
what is the best way to deal with this problem without using a plugin?
This code works with post types (posts, pages, products). Change filename and ads alt, title, caption and description meta to image.
But when its about attributes, categories keeps the filename and add it to alt, title, etc.
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
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 was try to find a way to take the title from attribute or category name to add it to metas but no luck. If you have any idea i do appreciate it.
I'm not so good to WordPress codex.
Hope this code help.

How to upload images to Wordpress programatically but prevent them showing up in Media Library?

So, I'm having a form with two image fields () and I've created a function that uploads the file really nice and neat. All of the files (only images allowed) are shown in Media Library.
But now I need them not to be visible in Media Library.
This is the function I use, and I even had wp_insert_attachment in it and now have it commented, hoping that it will be enough.
The images still show up in Media.
function insertImage ($file){
$wordpress_upload_dir = wp_upload_dir();
$i = 1; // number of tries when the file with the same name is already exists
$upload_dir_custom = $wordpress_upload_dir['basedir']."/custom-folder";
if (!file_exists($upload_dir_custom)) {
mkdir( $upload_dir_custom,0755,true) ;
}
$new_file_path = $upload_dir_custom;
$new_file_mime = mime_content_type( $file['tmp_name'] );
if( empty( $file ) )
die( 'File is not selected.' );
if( $file['error'] )
die( $file['error'] );
if( $file['size'] > wp_max_upload_size() )
die( 'Image is too large!.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
if($i>1){
$new_file_path = $wordpress_upload_dir['basedir'] . '/sponsor-info/' . $i . '_' .$file['name'];
}else{
$new_file_path = $wordpress_upload_dir['basedir'] . '/sponsor-info/'.$file['name'];
}
}
if( move_uploaded_file( $file['tmp_name'], $new_file_path ) ) {
$image_url = $wordpress_upload_dir['url'] . '/sponsor-info/' . basename( $new_file_path);
return $image_url;
}
}

WordPress; File renaming on upload

I'm trying to rename files while uploading them to WordPress and I want them to get the name of sanitized post title.
Basically I want to do same thing as here, but unfortunately when I use the code from this answer - I don't get the value of $post variable.
The only thing I get is "empty" name with some numbers at the end and the file extension, e.g. "-5263.png", which increses with every new file.
For some reason I don't get the $post value which would give me the post title and it just changes the file name to... well, nothing and just adding some numbers at the end, so it doesn't overrite any other file.
I really would like to know what's wrong with my code:
function new_filename( $filename, $filename_raw ) {
global $post;
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$new = $post->post_title;
if ( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new . $ext;
}
add_filter( 'sanitize_file_name', 'new_filename', 10 );
Thank you in advance for your help.
I've made a plugin a long time ago called File Renaming on Upload that can help you on this, but if you are searching for help with your code i can say that you can try a different approach to get the post variable. Try this instead:
function get_post() {
global $post;
$post_obj = null;
if( !$post ){
$post_id = isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : false;
if ( $post_id && is_numeric( $post_id ) ) {
$post_obj = get_post( $post_id );
}
}else{
$post_obj = $post;
}
return $post_obj;
}
Once you get your post variable, you don't need to use the post_title like that. You can use
$post->post_name
And then you don't need to use sanitize_file_name() function

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' );

How to get data in for loop

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];
}

Categories