デバイスによるアイキャッチ画像サイズ変更(Astraテーマ)

Astra_screenshot

Webサイトの表示速度を改善する方法の1つに、表示する画像サイズを適切な大きさにするというのがあります。

今回はWordPressのAstraテーマ使用時に、PC用とスマホ用でアイキャッチ画像のサイズを分けて表示する方法をご紹介します。

※WordPressの管理画面の「設定>メディア」 で、中サイズ(medium)の画像を作成する設定にしていることが前提です。

どの Astra テーマファイルでアイキャッチ画像サイズを指定しているか?

Astraのテーマファイルを見たところ、/wp-content/themes/astra/inc/markup-extras.php というファイルの astra_get_post_thumbnail() 関数と astra_single_post_entry_featured_image() 関数でアイキャッチ画像サイズが定義されていることが分かりました。

PHP
// 前略
/**
 * Astra get post thumbnail image.
 */
if ( ! function_exists( 'astra_get_post_thumbnail' ) ) {

        /**
         * Astra get post thumbnail image
         *
         * @since 1.0.15
         * @param string  $before Markup before thumbnail image.
         * @param string  $after  Markup after thumbnail image.
         * @param boolean $echo   Output print or return.
         * @return string|void
         */
        function astra_get_post_thumbnail( $before = '', $after = '', $echo = true ) {

                $output = '';

                $check_is_singular = is_singular();
                $check_is_archive  = ( is_archive() || is_search() || is_home() );

                $featured_image = true;
                $post_type      = strval( get_post_type() );

                if ( $check_is_singular ) {
                        $is_featured_image = astra_get_option_meta( 'ast-featured-img' );
                } else {
                        $is_featured_image = astra_get_option( 'ast-featured-img' );
                }

                $featured_image_size = 'large';
                if ( $check_is_archive ) {
                        $featured_image_size = astra_get_option( 'blog-image-size', 'large' );
                }

                if ( 'disabled' === $is_featured_image ) {
                        $featured_image = false;
                }

                $featured_image = apply_filters( 'astra_featured_image_enabled', $featured_image );

                $blog_post_thumb   = astra_get_option( 'blog-post-structure' );
                $single_post_thumb = astra_get_option( 'ast-dynamic-single-' . $post_type . '-structure', array( 'ast-dynamic-' . $post_type . '-post-title', 'ast-dynamic-' . $post_type . '-post-meta' ) );

                if ( ( ( ! $check_is_singular && in_array( 'image', $blog_post_thumb ) ) || ( $check_is_singular && in_array( 'ast-dynamic-single-' . $post_type . '-image', $single_post_thumb ) ) || is_page() ) && has_post_thumbnail() ) {

                        if ( $featured_image && ( ! ( $check_is_singular ) || ( ! post_password_required() && ! is_attachment() && has_post_thumbnail() ) ) ) {

                                $image_size = $check_is_singular ? astra_get_option( 'ast-dynamic-single-' . $post_type . '-article-featured-image-size', 'large' ) : $featured_image_size;
                                $post_thumb = apply_filters(
                                        'astra_featured_image_markup',
                                        get_the_post_thumbnail(
                                                get_the_ID(),
                                                apply_filters( 'astra_post_thumbnail_default_size', $image_size ),
                                                apply_filters( 'astra_post_thumbnail_itemprop', '' )
                                        )
                                );

                                if ( '' != $post_thumb ) {
                                        $output .= '<div class="post-thumb-img-content post-thumb">';
                                        if ( ! $check_is_singular ) {
                                                $output .= apply_filters(
                                                        'astra_blog_post_featured_image_link_before',
                                                        '<a ' . astra_attr(
                                                                'article-image-url',
                                                                array(
                                                                        'class' => '',
                                                                        'href'  => esc_url( get_permalink() ),
                                                                )
                                                        ) . ' >'
                                                );
                                        }
                                        $output .= $post_thumb;
                                        if ( ! $check_is_singular ) {
                                                $output .= apply_filters( 'astra_blog_post_featured_image_link_after', '</a>' );
                                        }
                                        $output .= '</div>';
                                }
                        }
                }

                if ( ! $check_is_singular ) {
                        $output = apply_filters( 'astra_blog_post_featured_image_after', $output );
                }

                $output = apply_filters( 'astra_get_post_thumbnail', $output, $before, $after );

                if ( $echo ) {
                        echo $before . $output . $after; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                } else {
                        return $before . $output . $after;
                }
        }
}

// 後略
PHP
// 前略
/**
 * Render Featured Image for single post at 'astra_entry_before' hook before post <article>
 *
 * @since 4.4.0
 */
function astra_single_post_entry_featured_image() {
        $post_type           = strval( get_post_type() );
        $featured_image_size = astra_get_option( 'ast-dynamic-single-' . $post_type . '-article-featured-image-size', 'large' );

        if ( apply_filters( 'astra_post_featured_image_condition', ( has_post_thumbnail() ) ) ) {
                do_action( 'astra_article_featured_image_before' );

                $output     = '';
                $post_thumb = apply_filters(
                        'astra_article_featured_image_markup',
                        get_the_post_thumbnail(
                                /** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
                                absint( astra_get_post_id() ),
                                /** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
                                apply_filters( 'astra_post_featured_image_default_size', $featured_image_size ),
                                apply_filters( 'astra_post_featured_image_itemprop', '' )
                        )
                );
                if ( '' != $post_thumb ) {
                        $featured_image_width = 'layout-1' === astra_get_option( 'ast-dynamic-single-' . $post_type . '-layout', 'layout-1' ) ? astra_get_option( 'ast-dynamic-single-' . $post_type . '-article-featured-image-width-type', 'wide' ) : '';
                        $output              .= '<div class="ast-single-post-featured-section post-thumb ast-article-image-container--' . esc_attr( $featured_image_width ) . '">';
                        $output              .= $post_thumb;
                        $output              .= '</div>';
                }

                $output = apply_filters( 'astra_featured_post_thumbnail', $output );
                echo wp_kses_post( $output );

                do_action( 'astra_article_featured_image_after' );
        }
}
// 後略

ちなみに、
astra_get_post_thumbnail() 関数は 個別ページ用、
astra_single_post_entry_featured_image() 関数は 固定ページ用と分かれているみたいです。

それぞれ $image_size$featured_image_size にサイズを指定して、フィルターの引数に渡していることが分かります。
(print_r で $image_size$featured_image_size を出力してみたところ、文字列 ‘large‘ が出力されました。)

デバイスの条件分岐を加えて、この $image_size$featured_image_size に ‘full’ や ‘medium’ を入れてあげればアイキャッチ画像のサイズを変更できそうです。

ただ、/wp-content/themes/astra/inc/markup-extras.php は親テーマのファイルなので、直接編集してもテーマアップデート時に上書きされ消えてしまいます。

そこで、対策として

①子テーマを使用する
②フィルターフックを使用する

の2つを実施します。

子テーマを使用する

子テーマが未作成であれば作成します。
(子テーマの詳細な作成方法については割愛します)

「Child Theme Configurator」というプラグインを使うと手軽に子テーマを作成できます。

フィルターフックを使用する

子テーマの /wp-content/themes/astra-child/functions.php に以下の内容を記述します。

PHP
//スマートフォンを判別
function is_mobile(){
    $useragents = array(
        'iPhone', // iPhone
        'iPod', // iPod touch
        'Android.*Mobile', // 1.5+ Android *** Only mobile
        'Windows.*Phone', // *** Windows Phone
        'dream', // Pre 1.5 Android
        'CUPCAKE', // 1.5+ Android
        'blackberry9500', // Storm
        'blackberry9530', // Storm
        'blackberry9520', // Storm v2
        'blackberry9550', // Storm v2
        'blackberry9800', // Torch
        'webOS', // Palm Pre Experimental
        'incognito', // Other iPhone browser
        'webmate' // Other iPhone browser
    );
    $pattern = '/'.implode('|', $useragents).'/i';
    return preg_match($pattern, $_SERVER['HTTP_USER_AGENT']);
}

// アイキャッチ画像サイズの適正化(モバイル端末とそれ以外)
// 投稿ページ用
function optimize_post_thumbnail_default_size( $image_size ) {
        if( is_mobile() ) {
                $image_size = 'medium';
        } else {
                $image_size = 'full';
        }
        return $image_size;
}
add_filter( 'astra_post_thumbnail_default_size', 'optimize_post_thumbnail_default_size' );

// 固定ページ用
function optimize_featured_image_size( $featured_image_size ) {
        if( is_mobile() ) {
                $featured_image_size = 'medium';
        } else {
                $featured_image_size = 'full';
        }
        return $featured_image_size;
}
add_filter( 'astra_post_featured_image_default_size', 'optimize_featured_image_size' );

スマホかどうかを判別するために is_mobile() 関数を作成しています。

また、optimize_post_thumbnail_default_size() 関数と optimize_featured_image_size() 関数で、スマホの場合は中サイズ(medium)、それ以外はフルサイズ(full)を指定し、それぞれ ‘astra_post_thumbnail_default_size‘ フィルターと ‘astra_post_featured_image_default_size‘ フィルターに追加しています。

※分かりやすくするために条件分岐をあえてシンプルにしていますが、実際には分岐がより複雑になります。

上部へスクロール