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' );
}
Related
I Want to loop all attachment url and save new html.
Sorry, I only script kiddies. I only understand some code.
This my script php
function get_all_image_clickable($content) {
global $post;
$args_img = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
"what_to_show" =>"posts",
"showposts" =>-1,
"post_mime_type" =>"image"
);
$attachments = get_posts($args_img);
$i = 0;
$dom = new DOMDocument('UTF-8');
#$dom->loadHTML( utf8_decode($content) ); // Decode to simple ISO to avoid accent errors
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
if( count($images) > 0 ) {
foreach ($images as $image) {
$width = $image->getAttribute('width'); // get the widths of each image
if( $width >= 860) { // if image is less than 860, add their old classes back in plus our new class
$clone_img = $image->cloneNode(); //clone node images
// Create DIV container
foreach ($attachments as $attachment) {
$parent = get_post($post->post_parent);
if($parent->post_status == "publish"){
$image_wrap = $dom->createElement('a');
$image_wrap->setAttribute('class', 'img-gallery' );
$image_wrap->setAttribute('href', get_attachment_link($attachment->ID));
}
$i++;
wp_reset_postdata();
}
$image_wrap->appendChild( $clone_img ); // Add to image to new container
$image->parentNode->replaceChild( $image_wrap, $image ); // Replace img object with all new elements
}
} // end if count
$content = $dom->saveHTML();
}
return $content;
}
add_filter( 'the_content' , 'get_all_image_clickable' , 15 );
i want to get all attachment url on its own image.
Sorry, my english bad.
I am using the wp-insert post function to dynamically generate pages from a website I am working on. However, I have been getting these no title posts that increase every time I refresh the page along with the actual pages that are generated from my code.
I have tried solving this by adding a hook into my page creation process, however this does not seem to do anything. I was wondering how I can only create the pages I need without these no title posts appearing.
My code:
if( !class_exists("PageCreator")) {
class PageCreator
{
public function __construct()
{
add_action('init', array($this, 'AddThisPage'));
}
public function AddThisPage()
{
$dirName = "/zotpull/resources/temp/";
$filename = dirname(__DIR__, 2) . $dirName . "useData.txt";
$theFile = fopen($filename, "r");
$msg = fread($theFile, filesize($filename));
fclose($theFile);
$links = explode("\n", $msg);
foreach( array_slice($links, 0, count($links) -1) as $item ) {
$item = str_replace("/","-",$item);
$str2 = substr($item, 5);
$page = array(
'page_template' => 'datePage.php', //Sets the template for the page.
'post_title' => $str2, //The title of your post.
'post_status' => 'publish',
'post_type' => 'page'
);
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$page_exists = post_exists($page['post_title']);
if ($page_exists == 0) {
$insert = wp_insert_post($page);
}
}
}
}
}
Try to use wp_update_post after wp_insert_post. check the below code.
if( !class_exists("PageCreator")) {
class PageCreator{
public function __construct()
{
add_action('init', array($this, 'AddThisPage'));
}
public function AddThisPage()
{
$dirName = "/zotpull/resources/temp/";
$filename = dirname(__DIR__, 2) . $dirName . "useData.txt";
$theFile = fopen($filename, "r");
$msg = fread($theFile, filesize($filename));
fclose($theFile);
$links = explode("\n", $msg);
foreach( array_slice($links, 0, count($links) -1) as $item ) {
$item = str_replace("/","-",$item);
$str2 = substr($item, 5);
$page = array(
'page_template' => 'datePage.php', //Sets the template for the page.
'post_title' => $str2, //The title of your post.
'post_status' => 'publish',
'post_type' => 'page'
);
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$page_exists = post_exists($page['post_title']);
if ($page_exists == 0) {
$insert = wp_insert_post($page);
$my_post = array(
'ID' => $insert,
'post_title' => $str2
);
wp_update_post( $my_post );
}
}
}
}
}
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' );
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];
}
I have a gallery which should display 3 columns, the first two columns have a certain class and work absolutely fine but I am trying to add a "last class" to my third column - for some reason it's not working. Find my code below:
<?php
$mod =1;
if ( $images = get_posts(array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'numberposts' => -1,
'post_mime_type' => 'image',)))
{
foreach( $images as $image ) {
$attachmenturl=wp_get_attachment_url($image->ID);
$attachmentimage=wp_get_attachment_image_src( $image->ID, full );
$imageDescription = apply_filters( 'the_description' , $image->post_content );
$imageTitle = apply_filters( 'the_title' , $image->post_title );
if ($mod % 3 == 0) {
$class = "gallery-entry-img-last";
}else{
$class = "gallery-entry-img";
}
echo '<div class="'.$class.'"><div class="gallery-entry-img-l"><a rel="next" href="' . $attachmentimage[0] . '"><span class="rollover" ></span><img src="library/tools/timthumb.php?src=' . $attachmentimage[0] . '&w=270&h=198" alt="" /></div></div>';
}
$mod++;
}
else {
echo "No Image";
}
?>
Some expert advise would be greatly appreciated.
increment your $mod variable inside foreach loop, like:
foreach(.....) {
......
$mod++;
}