【WordPress】プラグインなしでリンクカード(ブログカード)を実装する方法

/

WordPressでリンクカード(ブログカード)を表示したいけど、Pz-LinkCardなどのプラグインは使いたくない。そんなときにfunctions.phpとCSSだけで実装する方法です。

なぜプラグインを使わないのか?

  • 不要なCSS/JSの読み込みを減らして表示速度を改善
  • デザインを完全にコントロールできる
  • プラグインの更新停止リスクを回避

実装方法

1. functions.phpにショートコードを追加

function blog_card_shortcode($atts) {
    extract(shortcode_atts(array(
        'url'   => '',
        'title' => '',
    ), $atts));

    $id = url_to_postid($url);
    $no_image = get_template_directory_uri() . '/images/no-image.png';

    if (empty($title)) {
        $title = esc_html(get_the_title($id));
    }

    $img_url = get_the_post_thumbnail_url($id, 'medium');
    if (!$img_url) {
        $img_url = $no_image;
    }

    return '
    <div class="blog-card">
        <a href="' . esc_url($url) . '">
            <div class="blog-card-thum" style="background-image:url(' . esc_url($img_url) . ')"></div>
            <div class="blog-card-content">
                <p class="blog-card__ttl">' . esc_html($title) . '</p>
            </div>
        </a>
    </div>';
}
add_shortcode('blogcard', 'blog_card_shortcode');

2. CSSを追加

.blog-card {
    background-color: #f4f4f4;
    border-radius: 5px;
    border: 1px solid #ddd;
    margin: 30px 0;
}

.blog-card a {
    display: flex;
    align-items: flex-start;
    padding: 10px;
    text-decoration: none;
    color: inherit;
    transition: opacity 0.3s;
}

.blog-card a:hover {
    opacity: 0.7;
}

.blog-card-thum {
    width: 140px;
    height: 80px;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    margin-right: 10px;
    border-radius: 3px;
    flex-shrink: 0;
}

.blog-card-content {
    flex: 1;
}

.blog-card__ttl {
    font-weight: bold;
    font-size: 16px;
    line-height: 1.5;
    margin: 0;
}

@media screen and (max-width: 767px) {
    .blog-card-thum {
        width: 100px;
        height: 70px;
    }

    .blog-card__ttl {
        font-size: 14px;
    }
}

3. 記事内で使う

[blogcard url="https://example.com/your-post/"]

タイトルを手動指定したい場合:

[blogcard url="https://example.com/" title="外部サイトのタイトル"]

注意点

  • この方法は内部リンク向け。外部URLの場合はurl_to_postid()が使えないので、titleを手動で指定する必要がある
  • テーマを変更した場合はfunctions.phpの記述を移行する必要がある

補足:WordPress 5.0以降のブロックエディタ

WordPress 5.0以降のブロックエディタ(Gutenberg)では、URLを貼り付けるだけで自動的に埋め込みカードが生成されます。新規でWordPressを構築する場合は、まずブロックエディタの標準機能を試してみてください。

ショートコードで自作するのは、クラシックエディタを使っている場合や、デザインを細かく制御したい場合に有効な方法です。