Автозаполнение алт изображений на странице записей
function bygi_fill_alts_batch() {
$offset = (int) get_option('bygi_alt_offset', 0);
$limit = 25;
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => $limit,
'offset' => $offset
]);
if (empty($posts)) {
delete_option('bygi_alt_offset');
wp_clear_scheduled_hook('bygi_fill_alts_event');
return;
}
foreach ($posts as $post) {
$content = $post->post_content;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);
$xpath = new DOMXPath($dom);
$imgs = $xpath->query('//img');
foreach ($imgs as $img) {
if ($img->getAttribute('alt')) continue;
$headingText = '';
$node = $img;
while ($node) {
while ($node->previousSibling) {
$node = $node->previousSibling;
if (in_array($node->nodeName, ['h2','h3','h4'])) {
$headingText = trim($node->textContent);
break 2;
}
if ($node->hasChildNodes()) {
foreach (['h2','h3','h4'] as $tag) {
$elements = $node->getElementsByTagName($tag);
if ($elements->length > 0) {
$headingText = trim($elements->item($elements->length - 1)->textContent);
break 3;
}
}
}
}
$node = $node->parentNode;
}
if ($headingText) {
$img->setAttribute('alt', $headingText);
}
}
$new_content = $dom->saveHTML();
$new_content = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $new_content);
if ($new_content !== $content) {
wp_update_post([
'ID' => $post->ID,
'post_content' => $new_content
]);
}
}
update_option('bygi_alt_offset', $offset + $limit);
}
add_action('bygi_fill_alts_event', 'bygi_fill_alts_batch');
add_action('admin_init', function() {
if (!current_user_can('administrator')) return;
bygi_fill_alts_batch();
});