gooodmark

goodなWebサイトを厳選ブックマーク!デザインやディレクションの参考にどうぞ。

724bookmark

WordPressのfunction.phpで常用するコード④(画像設定編)

アイキャッチ画像を使用

function.php


add_theme_support('post-thumbnails');
add_image_size('slide', 640, 400, true );
add_image_size('item', 300, 300, true );

画像リンク自動削除

function.php


add_filter( 'the_content', 'attachment_image_link_remove_filter' );
function attachment_image_link_remove_filter( $content ) {
$content = preg_replace( array('{<a(.*?)(wp-att|wp-content/uploads)[^>]*><img}', '{ wp-image-[0-9]*" /></a>}'), array('<img','" />'), $content );
return $content;
}

すでに公開されている記事の画像リンクを強制削除

function.php


function remove_img_attr($html, $id, $alt, $title, $align, $size) {
$html = preg_replace('/title=['"]([^'"]+)['"]/i', '', $html);
return preg_replace('/ class=['"]([^'"]+)['"]/i', '', $html);
}
add_filter('get_image_tag','remove_img_attr', 10, 6);

画像挿入Class&Title自動削除

function.php


function remove_img_attr($html, $id, $alt, $title, $align, $size) {
$html = preg_replace('/title=['"]([^'"]+)['"]/i', '', $html);
return preg_replace('/ class=['"]([^'"]+)['"]/i', '', $html);
}
add_filter('get_image_tag','remove_img_attr', 10, 6);

「添付ファイルの表示設定」非表示

function.php


add_action( 'admin_print_styles', 'admin_css_custom' );
function admin_css_custom() {
echo '<style>.attachment-details label[data-setting="caption"], .attachment-details label[data-setting="description"], .attachment-details label[data-setting="alt"], table.compat-attachment-fields, div.attachment-display-settings h3, div.attachment-display-settings .setting span, div.attachment-display-settings .setting select { display: none; } ';
}

画像トリミング位置指定

function.php


function my_awesome_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ){
if( false ) return $payload;

if ( $crop ) {
$aspect_ratio = $orig_w / $orig_h;
$new_w = min($dest_w, $orig_w);
$new_h = min($dest_h, $orig_h);

if ( !$new_w ) $new_w = intval($new_h * $aspect_ratio);
if ( !$new_h ) $new_h = intval($new_w / $aspect_ratio);

$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
$crop_w = round($new_w / $size_ratio);
$crop_h = round($new_h / $size_ratio);

$s_x = 0;
$s_y = 0;
} else {
$crop_w = $orig_w;
$crop_h = $orig_h;

$s_x = 0;
$s_y = 0;

list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
}

if ( $new_w >= $orig_w && $new_h >= $orig_h ) return false;
return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}
add_filter( 'image_resize_dimensions', 'my_awesome_image_resize_dimensions', 10, 6 );