Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
// Outputs list of post ids and url for first image in post
// This script gathers data for images not already uploaded to WP
// Quick Usage
// 1. copy script and lib below to your WP directory
// 2. install wp-cli from: http://wp-cli.org
// 3. Run script: wp eval-file get-posts-no-imgs.php >posts-data.txt
// uses SimpleHTML class, include lib from:
// http://sourceforge.net/projects/simplehtmldom/
require_once("SimpleHTML.class.php");
$args = array(
"category_name" => "photography",
"nopaging" => true
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// bail if already have featured image
if ( has_post_thumbnail() ) {
continue;
}
$post_id = get_the_ID();
$content = get_the_content();
// extract first image out of content and set as thumbnail
$img = get_first_image( $content );
if ( $img ) {
print "$post_id: $img \n";
}
}
}
// extract the first image out of an html block passed in
function get_first_image( $block ) {
$html = str_get_html( $block );
if ( $html ) {
$img = $html->find( 'img', 0 );
if ( $img && ( $img !== null ) ) {
return $img->src;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment