Skip to content

Instantly share code, notes, and snippets.

@chrissnyder2337
Created March 25, 2015 16:38
Show Gist options
  • Save chrissnyder2337/66a1810a007081c0cb1a to your computer and use it in GitHub Desktop.
Save chrissnyder2337/66a1810a007081c0cb1a to your computer and use it in GitHub Desktop.
Add a class to the first image field of all blog articles on a Drupal 7 site.
<?php
/**
* Created by PhpStorm.
* User: chris
* Date: 3/25/15
* Time: 11:44 AM
*/
# Bootstrap start
define('DRUPAL_ROOT', '.');
//$_SERVER['REMOTE_ADDR'] = "localhost"; // Necessary if running from command line
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
# Bootstrap end
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'blog')
->execute();
$nodeIds = array_keys($result['node']);
foreach ($nodeIds as $node_id) {
$node_wrapper = entity_metadata_wrapper('node', $node_id);
$body = $node_wrapper->body->value->raw();
$new_body = add_class_to_first_img_tag ($body);
$node_wrapper->body->value = $new_body;
$node = $node_wrapper->value();
field_attach_update('node', $node);
//$node_wrapper->save();
print $node_id . '<br/>';
}
function add_class_to_first_img_tag ($string) {
if(strpos($string, '<img')){
$split_point = strpos($string, '<img') + 4;
$first_half = substr($string, 0, $split_point);
$second_half = substr($string, $split_point);
$new_string = $first_half . ' class="legacy" ' . $second_half;
return $new_string;
} else {
return $string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment