Skip to content

Instantly share code, notes, and snippets.

@cdolek
Last active August 29, 2015 14:01
Show Gist options
  • Save cdolek/f49af9b25ab99ff79e8e to your computer and use it in GitHub Desktop.
Save cdolek/f49af9b25ab99ff79e8e to your computer and use it in GitHub Desktop.
Download attached images from a wordpress blog and save them into folders based on post title under uploads dir
<?php
/**
* Template Name: worker
*/
$args = array(
'posts_per_page'=> '-1',
'post_type'=> 'post',
'post_status' => array('publish'),
'order' => 'ASC',
'orderby' =>'date'
);
$r = new WP_Query($args);
function download_image ($url, $the_filename, $path) {
$upload_dir = wp_upload_dir();
$path = $upload_dir['path'] . '/' . $path . '/';
if(!file_exists($path)) mkdir($path);
$cookie = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Debian) Firefox/0.10.1");
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLINFO_EFFECTIVE_URL, true);
curl_setopt($ch, CURLOPT_REFERER, "http://tomakefast.com");
curl_setopt($ch, CURLOPT_POST, false);
$rawdata=curl_exec($ch);
curl_close($ch);
file_put_contents( $path . $the_filename, $rawdata);
}
?>
<?php if ( $r->have_posts() ) : while ( $r->have_posts() ) : $r->the_post(); ?>
<!-- post -->
<h1><?php the_title(); ?></h1>
<p><?php echo mysql2date( 'F j, Y', $post->post_date ); ?></p>
<p><?php the_category(); ?></p>
<blockquote><?php the_content(); ?></blockquote>
<?php
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$filename = basename($attachment->guid);
$sanitized_title = sanitize_title(get_the_title($post->ID));
download_image($attachment->guid, $filename, $sanitized_title);
echo ('<p>'. $attachment->guid .'</p>' );
}
}
?>
<hr/>
<?php endwhile; ?>
<?php else: ?>
<!-- no posts found -->
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment