アイキャッチ画像リンク機能の追加

アイキャッチ画像リンク設定サムネ

制作概要

サイトの添削時に支援員の方がサムネイル画像をクリックしている様子を見て公開サイトが存在する場合、直接アクセスできる方が便利だと考えました。

そこで、WordPressの標準機能では設定できないアイキャッチ画像のリンク先を、記事ごとに指定できる独自機能を実装しました。

エディターの投稿編集画面にリンク先URLの入力欄を追加し、記事ごとにリンク先を設定できる仕組みを構築しています。

また、リンク先が設定された画像には「View Site」のテキストと外部リンクアイコンを表示し、リンク先があることを視覚的に伝えることで意図しないページ遷移を防ぐ工夫を加えました。

実装所要時間:約7時間
※要件検討・実装・動作確認に要した時間。
※記事作成にかかった時間は含みません。

実装内容

1.投稿編集画面にURL入力欄を追加(エディター側のJs)

編集画面の投稿タブ内に設定パネルを追加し、リンク先URLを入力・更新できるようにしています。入力欄には現在の設定値を表示し、URLが入力されている場合はリンク先を確認できるリンクも表示します。

featured-image-link-editor.js
(function (wp) {

    /* ----------------------------------------
       使用するWordPressの機能
    ---------------------------------------- */

    const { registerPlugin } = wp.plugins;
    const { PluginDocumentSettingPanel } = wp.editPost;
    const { TextControl, ExternalLink } = wp.components;
    const { createElement: el } = wp.element;
    const { useSelect, useDispatch } = wp.data;

    /* ----------------------------------------
       アイキャッチ画像リンク設定パネル
    ---------------------------------------- */

    function FeaturedImageLinkPanel() {

        // 投稿に保存されているメタデータを取得
        const meta = useSelect(function (select) {
            return (
                select('core/editor').getEditedPostAttribute('meta') || {}
            );
        }, []);

        // 投稿内容を更新する機能
        const { editPost } = useDispatch('core/editor');

        // 現在設定されているURL
        const url = meta._atsu_featured_image_link || '';

        /* URLの更新 */
        function updateUrl(value) {

            editPost({
                meta: {
                    ...meta,
                    _atsu_featured_image_link: value,
                },
            });
        }

        /* ----------------------------------------
           パネルの表示
        ---------------------------------------- */

        return el(
            PluginDocumentSettingPanel,
            {
                name: 'atsu-featured-image-link',
                title: 'アイキャッチ画像リンク',
                className: 'atsu-featured-image-link-panel',
            },

            // URL入力欄
            el(TextControl, {
                label: 'リンク先URL',
                type: 'url',
                value: url,
                placeholder: 'https://example.com/',
                help: '未入力の場合はリンクを設定しません。',
                onChange: updateUrl,
            }),

            // URLが入力されている場合のみ確認リンクを表示
            url
                ? el(
                    'p',
                    {},
                    el(
                        ExternalLink,
                        {
                            href: url,
                        },
                        'リンク先を確認する'
                    )
                )
                : null
        );
    }

    /* ----------------------------------------
       プラグイン登録
    ---------------------------------------- */
    registerPlugin(
        'atsu-featured-image-link',
        {
            render: FeaturedImageLinkPanel,
        }
    );
})(window.wp);

PluginDocumentSettingPanel を使用して投稿編集画面に設定パネルを追加し、TextControl でリンク先URLの入力欄を作成しています。

URL追加部分

入力欄には投稿に設定されているURLを表示し、変更した内容を投稿の編集データに反映します。またURLが入力されている場合はリンク先を確認できるリンクを表示し、未入力の場合は表示しないようにしています。

2.URLの保存とアイキャッチ画像へのリンク設定(PHP)

入力したURLを投稿のメタデータとして保存できるように設定し、公開ページのアイキャッチ画像にリンク先を反映する処理を実装しました。

featured-image-link.php
<?php
/* ----------------------------------------
   アイキャッチ画像リンク設定
---------------------------------------- */

/* カスタムフィールドの登録 */

function AtsuPortfolioTheme_register_featured_image_link_meta() {

    // 投稿タイプにカスタムフィールドを追加
    add_post_type_support( 'post', 'custom-fields' );

    // REST API経由でメタデータを利用できるようにする
    register_post_meta(
        'post',
        '_atsu_featured_image_link',
        array(
            'type'              => 'string',
            'single'            => true,
            'default'           => '',
            'show_in_rest'      => true,
            'sanitize_callback' => 'esc_url_raw',
            'auth_callback'     => function() {
                return current_user_can( 'edit_posts' );
            },
        )
    );
}
add_action(
    'init',
    'AtsuPortfolioTheme_register_featured_image_link_meta'
);

/* ----------------------------------------
   アイキャッチ画像の表示とリンク設定
---------------------------------------- */

function AtsuPortfolioTheme_render_featured_image_link(
    $block_content,
    $block
) {

    // 個別投稿ページ以外では処理しない
    if ( ! is_singular( 'post' ) ) {
        return $block_content;
    }

    // 投稿のアイキャッチ画像ブロック以外は処理しない
    if (
        ! isset( $block['blockName'] ) ||
        $block['blockName'] !== 'core/post-featured-image'
    ) {
        return $block_content;
    }

    // 現在の記事IDを取得
    $post_id = get_queried_object_id();

    if ( ! $post_id ) {
        return $block_content;
    }

    // 現在処理している投稿が、個別記事の投稿自身でない場合は処理しない
    if ( get_the_ID() !== $post_id ) {
        return $block_content;
    }

    // アイキャッチ画像が未設定の場合はデフォルト画像を表示
    if ( ! has_post_thumbnail( $post_id ) ) {

        // デフォルト画像のパス
        $default_image = get_template_directory_uri()
            . '/assets/images/common/no_image_black.png';

        // デフォルト画像に記事自身へのリンクを設定
        return sprintf(
            '<figure class="wp-block-post-featured-image is-default-thumbnail">
                <a href="%1$s">
                    <img src="%2$s" alt="">
                </a>
            </figure>',
            esc_url( get_permalink( $post_id ) ),
            esc_url( $default_image )
        );
    }

    // カスタムリンクのURLを取得
    $url = get_post_meta(
        $post_id,
        '_atsu_featured_image_link',
        true
    );

    // URLが未設定なら通常表示
    if ( empty( $url ) ) {
        return $block_content;
    }

    // figureタグの内側にリンクを追加
    return preg_replace_callback(
        '/(<figure\b[^>]*>)(.*?)(<\/figure>)/s',
        function( $matches ) use ( $url ) {

            return sprintf(
                '%1$s<a href="%2$s" target="_blank" rel="noopener noreferrer">%3$s</a>%4$s',
                $matches[1],
                esc_url( $url ),
                $matches[2],
                $matches[3]
            );

        },
        $block_content,
        1
    );
}
add_filter(
    'render_block',
    'AtsuPortfolioTheme_render_featured_image_link',
    10,
    2
);


/* ----------------------------------------
   アイキャッチ未設定時のデフォルト画像
---------------------------------------- */

// 投稿記事のアイキャッチ未設定時デフォルト画像の指定
add_filter( 'render_block', function( $block_content, $block ) {
    if (
        $block['blockName'] === 'core/post-featured-image' &&
        ! has_post_thumbnail()
    ) {
        $default_image = get_template_directory_uri() . '/assets/images/common/no_image_black.png';

        return sprintf(
            '<figure class="wp-block-post-featured-image is-default-thumbnail">
                <a href="%s">
                    <img src="%s" alt="">
                </a>
            </figure>',
            esc_url( get_permalink() ),
            esc_url( $default_image )
        );
    }

    return $block_content;
}, 10, 2 );

URLの保存設定

register_post_metaを使用して、リンク先URLを記事ごとに保存できるように設定しています。また、記事編集画面のJavaScriptからURLを利用できるようにし、保存する値をURLとして扱えるように整える処理や、編集権限の確認を設定しています。

アイキャッチ画像へのリンク設定

render_blockフックを使用して、個別記事ページのアイキャッチ画像にリンクを設定する処理を追加しています。記事に保存されたURLを取得し、URLが設定されている場合のみアイキャッチ画像をリンクタグで囲む仕組みです。

上記のコードによって、下記のようなHTMLが出力されます。URLが設定されていない場合は、アイキャッチ画像にリンクを設定せずそのまま表示します。

HTML出力例
<figure class="wp-block-post-featured-image">
    <a href="リンク先URL" target="_blank" rel="noopener noreferrer">
        <img src="アイキャッチ画像のURL" alt="画像の説明">
    </a>
</figure>

また、アイキャッチ画像が設定されていない記事では、下記のようなデフォルト画像を表示する処理も実装しています。

画像指定なし黒バージョン

もし当サイトと同じ画像を用いたい場合は、右クリックで「名前を付けて画像を保存」を行い、テーマ内のassets/images/common/フォルダに配置してください。

なお、この処理が不要な場合は、コードをコピーした後、末尾の「アイキャッチ未設定時のデフォルト画像」から始まる処理を削除してください。

3.アイキャッチ画像の装飾(CSS)

リンク先が設定されたアイキャッチ画像のみに「View Site」のテキストと外部リンクアイコンを表示しリンク先があることを視覚的に伝えることで、意図しないページ遷移を防ぐための装飾を実装しました。

single-common.css
/* 最初のアイキャッチ画像にだけ指定 */
.article>.wp-block-post-featured-image:first-of-type {
    max-width: inherit;
    box-shadow: rgba(255, 255, 255, 0.12) 0px 1px 1px 0px inset,
        rgba(50, 50, 93, 0.12) 0px 50px 100px -20px,
        rgba(0, 0, 0, 0.12) 0px 30px 60px -30px;
    border-top: 1px solid var(--line-black-color) !important;
    border-bottom: 1px solid var(--line-black-color) !important;
    margin: 48px -16px 0px !important;
}

/* 作品URLがある記事の場合、リンクさせる
       1312px以下のホバー時の処理 */
.article>.wp-block-post-featured-image:first-of-type a {
    position: relative;
    display: block;
}

/* テキストと背景部分 */
.article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a::before {
    font-weight: 400 !important;
    letter-spacing: 0.16em !important;
    content: "View Site";
    position: absolute;
    top: 0px;
    right: 0px;
    padding: 6px 46px 6px 20px;
    color: #fff;
    background: linear-gradient(to left,
            rgb(0 0 0 / 0.88) 0%,
            rgb(0 0 0 / 0.64) 64%,
            transparent 100%);
    text-indent: 80px;
    font-size: 1rem;
    font-weight: 400;
    letter-spacing: 0.08em;
    opacity: 1;
    transition: opacity 0.3s ease;
}

/* 外部リンクアイコン */
.article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a::after {
    content: "";
    position: absolute;
    /* View Site の右側に配置 */
    top: 20px;
    right: 34px;
    width: 1.2rem;
    height: 1.2rem;
    background: url("../images/icons/arrow-square-out-white-light.svg") center / contain no-repeat;
    opacity: 1;
    transform: translate(1rem, -50%);
    transition: opacity 0.3s ease;
}

/* サムネなし */
.article .is-default-thumbnail {
    margin-bottom: 80px;
}

/* 画像にはリンクさせず、通常カーソルを指定 */
.article>.wp-block-post-featured-image.is-default-thumbnail:first-of-type a {
    pointer-events: none;
    cursor: default;
}

/* タブレット以降 */
@media screen and (min-width: 1056px) {

    /* 最初のアイキャッチ画像にだけ指定 */
    .article>.wp-block-post-featured-image:first-of-type {
        max-width: 1024px;
        border: 1px solid var(--line-black-color) !important;
        margin: 48px auto 0px !important;
    }

    /* 作品URLがある記事の場合、リンクさせる
        それのホバー処理 */
    .article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a {
        position: relative;
        display: block;
    }

    /* テキストと背景部分 */
    .article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a::before {
        font-weight: 400;
        content: "View Site";
        position: absolute;
        inset: 0;
        display: grid;
        place-items: center;
        text-indent: -16px;
        color: #fff;
        background: rgb(0 0 0 / 0.64);
        font-size: 3rem;
        letter-spacing: 0.08em;
        opacity: 0;
        transition: opacity 0.3s ease;
        backdrop-filter: blur(8px);
        -webkit-backdrop-filter: blur(8px);
    }

    /* 外部リンクアイコン */
    .article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a::after {
        content: "";
        position: absolute;
        /* Visit Siteの右側に配置 */
        top: calc(50% - 1px);
        left: 50%;
        width: 3rem;
        height: 3rem;
        background: url("../images/icons/arrow-square-out-white-light.svg") center / contain no-repeat;
        opacity: 0;
        transform: translate(128px, -50%);
        transition: opacity 0.3s ease;
    }

    .article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a:hover::before,
    .article>.wp-block-post-featured-image:first-of-type:not(.is-default-thumbnail) a:hover::after {
        opacity: 1;
    }
}
記事ページサムネイルPC表示

画面幅に応じて表示方法を切り替え、PCでは画像にカーソルを合わせると、半透明の背景とぼかしを重ねてテキストとアイコンを表示します。

記事ページサムネイルスマホ・タブレット表示

スマホやタブレットなどホバー操作ができない端末では、画像の右上にテキストとアイコンを表示しリンク先があることを確認しやすくしています。

また、リンク先URLが設定されていない画像やアイキャッチ画像が設定されていない場合は、リンク用の装飾を表示しないようにしています。

まとめ

今回の制作では、WordPressの投稿編集画面にアイキャッチ画像のリンク先URLを設定する機能を追加しました。

拡張機能
アイキャッチ画像のリンク先設定
設定方法
投稿編集画面からURLを入力
主な機能
・URLの保存
・アイキャッチ画像へのリンク設定
表示機能
・「View Site」テキスト
・外部リンクアイコン
使用技術
・PHP
・JavaScript
・CSS
・WordPress
所要時間
約7時間

また、今回の制作を通じて、以下の点について学ぶことができました。

  • WordPressの投稿編集画面に独自の設定項目を追加する方法
  • 投稿メタデータを利用した記事ごとの設定値の保存
  • PHPによる標準ブロックの出力内容の拡張
  • CSSによるリンクの視認性と操作性の調整

今後の制作にも活用できる機能として、記事ごとにリンク先を設定できる仕組みを実装し公開サイトへのアクセス性と操作性の向上を図りました。