/ Wordpress / Вставка изображений в запись

Вставка изображений в запись

HIT

09.03.2018

2346

Для вставки изображения в запись в wordpress существует соответствующая функция с выводом верстки — image_send_to_editor.

Как изменить вывод верстки и делать отложенную загрузку изображений описано в статье Постепенная загрузка изображений.

Атрибуты изображений вставленных в запись

Добавить при вставке к изображениям атрибут title можно плагином Restore Image Title (4000+), в нем заключены две простые функции:

// добавляем к изображениям поста title
function lcb_restore_image_title( $html, $id ) {
	$attachment = get_post($id);
    if (strpos($html, "title=")) { return $html; }
    else {
		$mytitle = esc_attr($attachment->post_title);
		return str_replace('<img', '<img title="' . $mytitle . '" '  , $html);      
	}
}
add_filter( 'media_send_to_editor', 'lcb_restore_image_title', 15, 2 );

Атрибуты ссылки на изображение

Добавим класс ссылке:

function add_class_to_image_links($html, $attachment_id, $attachment) {
    $linkptrn = "/<a[^>]*>/";
    $found = preg_match($linkptrn, $html, $a_elem);
    
    if($found <= 0) return $html; // If no link, do nothing
    $a_elem = $a_elem[0];
    
    $is_attachment_link = strstr($a_elem, "wp-content/uploads/"); // Check to see if the link is to an uploaded image
    
    if($is_attachment_link === FALSE) return $html; // If link is to external resource, do nothing
	
    if(strstr($a_elem, "class=\"") !== FALSE){ // If link already has class defined inject it to attribute
        $a_elem_new = str_replace("class=\"", "class=\"YOUR-CLASS-HERE", $a_elem);
        $html = str_replace($a_elem, $a_elem_new, $html);
    }else{ // If no class defined, just add class attribute
        $html = str_replace("<a ", "<a class=\"YOUR-CLASS-HERE\" ", $html);
    }
    return $html;
}
add_filter('image_send_to_editor', 'add_class_to_image_links', 10, 3);</a[^>

Либо можно вывести произвольный атрибут

function add_class_to_image_links($html, $id, $attachment_id, $attachment) {
    $linkptrn = "/<a[^>]*>/";
    $found = preg_match($linkptrn, $html, $a_elem);
    
    if($found <= 0) return $html; // If no link, do nothing
    $a_elem = $a_elem[0];
    
    $is_attachment_link = strstr($a_elem, "wp-content/uploads/"); // Check to see if the link is to an uploaded image
    if($is_attachment_link === FALSE) return $html; // If link is to external resource, do nothing
 
    $image = get_post($id); //получаем объект, из которого можно взять title, caption, description
 
    $html = str_replace('<a ', '<a data-caption="'.$image->post_excerpt.'" ', $html);
    return $html;
}
add_filter('image_send_to_editor', 'add_class_to_image_links', 10, 3);</a[^>

$image — получаем объект, из которого можно взять:
$post->post_title — title (Заголовок)
$image->post_excerpt — caption (Подпись)
$image->post_content — descripion (Описание)

При необходимости можно получить alt изображения:

$image_alt = get_post_meta($id, '_wp_attachment_image_alt', true);
Можно вовсе отключить вставку caption (описано ниже) и перенастроить скрипты всплывающего текста и fancybox под атрибут data-caption.

Стили для всплывающего caption

.img-caption {display: inline-block; position: relative;}

.img-caption:after {
    content: attr(data-caption);
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background: #00000099;
    color: #fff;
    font-size: 0.9rem;
    padding: 15px 30px;
    opacity: 0;
    -webkit-transition: opacity 0.3s linear;
    transition: opacity 0.3s linear;
    -o-transition: opacity 0.3s linear;
}

.img-caption:hover::after {opacity: 1;}

a.img-caption img {display: block;}

Вставка caption

Переопределяем вставку caption, вместо шорткода, добавим в виде атрибута

// изменяем вывод caption
remove_filter( 'image_send_to_editor', 'image_add_caption', 20);

add_filter( 'image_send_to_editor', 'my_image_add_caption', 10, 8 );

function my_image_add_caption( $html, $id, $caption ) {
    $caption = apply_filters( 'image_add_caption_text', $caption, $id );

    if (strpos($html, "caption=")) { return $html; }
    else { return str_replace('<img', '<img caption="' . $caption . '"' , $html); }
}

Вставим caption в виде обертывающего div, чтобы комбинировать с функционалом всплывающих подсказок

add_filter( 'image_send_to_editor', 'my_image_add_caption', 10, 8 );

function my_image_add_caption( $html, $id, $caption, $align ) {
	$caption = apply_filters( 'image_add_caption_text', $caption, $id );
	if ( empty($align) ) $align = 'none';
	$shcode = '<div class="img-caption align' . $align . '" data-title="' . $caption . '">' . $html . '</div>';
	return apply_filters( 'image_add_caption_shortcode', $shcode, $html ); 
}

Отключить вставку caption

// Отключаем вставку caption
function caption_off() { return true; }
add_filter( 'disable_captions', 'caption_off' );

Удаляем лишние атрибуты

Как убрать домен из ссылки при вставке изображения описано здесь.

Убираем все классы вставляемых изображений:

// Удалить все классы изображения
add_filter('get_image_tag', 'strip_entire_image_class');
function strip_entire_image_class($html) {
	return preg_replace('/ class="(.*)"/', '', $html);
}

Убираем атрибуты высота и ширина:

// Удалить ширину и высоту изображения
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

Поделиться в соц. сетях:

  • Комментарии
  • Вложения

Добавить комментарий

Пока нет комментариев. Будь первым!

Вставка изображений в запись
Изменение контента при скроллинге
Рекомендации для васИзменение контента при скроллингеOpttour.ru
Спасибо! Наш менеджер свяжется с Вами в течении 5 минут.