この WordPress ブログで使用されているSNS共有ボタン&URLコピーボタン

Last Updated:2024年02月04日| | 17のコメント

この WordPress ブログにプラグインを使用せずに直接コードを作成する Naver, Facebook, Twitter 共有ボタンとURLコピーボタンを追加して使用しています。 より簡単にコードを管理し、一貫性を持つようにコードを最近更新しました。

Naver カフェでこのブログに使用されたURLコピーボタンを実装する方法についてお問い合わせいただいた方がいらっしゃって、このサイトで使用されているSNS共有ボタン&URLコピーボタンのコードを以下にまとめてみました。

[この記事は、2024年2月4日に最後に更新されました。 ]

この WordPress ブログで使用されているSNS共有ボタン&URLコピーボタン

この WordPress ブログで使用されているSNS共有ボタン&URLコピーボタン

現在このブログでは、 Naver、Facebook、Twitter共有ボタン、投稿URLコピーボタンがタイトルの下に表示されます。 カカオトーク共有ボタンも表示しましたが、効用性が落ちて削除しました。 カトク共有ボタンを追加するには、カカオデベロッパーページにアクセスしてデベロッパーアカウントにサインアップし、アプリケーションを作成する必要があります(この記事の「2021年8月追加:カカオトーク共有ボタンを追加する」を参照)。

このブログで使用されているソーシャルネットワーク共有ボタンのソースは次のとおりです。

HTMLコード

<!-- SNS Share Button -->
<div class="sns-go">
    <ul>
        <li>
            <a 
                href="#" 
                class="js-social-share" 
                data-url="http://share.naver.com/web/shareView.nhn?url=" 
                data-title="[공유] " 
                target="_blank" 
                alt="Naver에 공유" 
                rel="nofollow"
            >
                <svg height="35" width="35"  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 96 96" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><rect width="96.000002" height="96" rx="9" ry="9" fill="#1dc800" stroke-width="0"/><g transform="translate(.000001 0.000001)"><path d="M22.810019,26.075075h18.03984l16.57371,24.254979v-24.223106h17.944217v47.999999h-17.976097L40.881729,50.075074v24.095618h-18.16733Z" fill="#fff" stroke="#000" stroke-width="0"/></g></svg>
            </a>
        </li>

<li>
    <a 
        href="#" 
        class="js-social-share" 
        data-url="https://www.facebook.com/sharer/sharer.php?u=" 
        data-title="[공유] " 
        target="_blank" 
        alt="Facebook에 공유" 
        rel="nofollow"
    >
       <svg height="35" width="35" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
	 viewBox="0 0 408.788 408.788" xml:space="preserve">
<path style="fill:#475993;" d="M353.701,0H55.087C24.665,0,0.002,24.662,0.002,55.085v298.616c0,30.423,24.662,55.085,55.085,55.085
	h147.275l0.251-146.078h-37.951c-4.932,0-8.935-3.988-8.954-8.92l-0.182-47.087c-0.019-4.959,3.996-8.989,8.955-8.989h37.882
	v-45.498c0-52.8,32.247-81.55,79.348-81.55h38.65c4.945,0,8.955,4.009,8.955,8.955v39.704c0,4.944-4.007,8.952-8.95,8.955
	l-23.719,0.011c-25.615,0-30.575,12.172-30.575,30.035v39.389h56.285c5.363,0,9.524,4.683,8.892,10.009l-5.581,47.087
	c-0.534,4.506-4.355,7.901-8.892,7.901h-50.453l-0.251,146.078h87.631c30.422,0,55.084-24.662,55.084-55.084V55.085
	C408.786,24.662,384.124,0,353.701,0z"/>
</svg>
    </a>
</li>

<li>
    <a 
        href="#" 
        class="js-social-share" 
        data-url="https://twitter.com/intent/tweet?url=" 
        data-title="[공유] " 
        target="_blank" 
        alt="Twitter에 공유" 
        rel="nofollow"
    >
    <svg height="35" width="35" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 29.242 29.242" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><g><g><path d="M26.918,0.668h-24.592C1.039,0.668,0,1.756668,0,3.103095v24.370858C0,28.817237,1.039,29.908,2.326,29.908h24.592c1.281,0,2.324-1.090763,2.324-2.434047v-24.370858c0-1.346427-1.043-2.435095-2.324-2.435095ZM14.549,18.113926c.41.429599.908.646495,1.496.646495h4.227c.59,0,1.09.221087,1.51.659068.422.437982.629.966075.629,1.580087s-.209,1.141058-.629,1.577992c-.42.440077-.92.661164-1.508.661164h-4.227c-1.76,0-3.266-.656973-4.514-1.964631-1.25-1.309754-1.873-2.88565-1.873-4.729784v-8.934619c0-.632873.207-1.16411.623-1.594757.416-.428552.924-.644399,1.523-.644399.584,0,1.082.217943,1.5.65802.416.440077.623.965027.623,1.580087v2.238108h6.334c.592,0,1.094.218991,1.514.659068.426.437982.633.962931.633,1.580087c0,.610869-.209,1.14001-.629,1.580087-.42.436934-.92.656973-1.51.656973h-6.341v2.2182c0,.617156.205,1.14001.619,1.572753Z" transform="translate(0-.666)" fill="#42c8f4"/></g></g></svg>
    </a>
</li>
        <li>
            <a class="js-copy-btn">
                <svg width="35" height="35" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M172.5 131.1C228.1 75.51 320.5 75.51 376.1 131.1C426.1 181.1 433.5 260.8 392.4 318.3L391.3 319.9C381 334.2 361 337.6 346.7 327.3C332.3 317 328.9 297 339.2 282.7L340.3 281.1C363.2 249 359.6 205.1 331.7 177.2C300.3 145.8 249.2 145.8 217.7 177.2L105.5 289.5C73.99 320.1 73.99 372 105.5 403.5C133.3 431.4 177.3 435 209.3 412.1L210.9 410.1C225.3 400.7 245.3 404 255.5 418.4C265.8 432.8 262.5 452.8 248.1 463.1L246.5 464.2C188.1 505.3 110.2 498.7 60.21 448.8C3.741 392.3 3.741 300.7 60.21 244.3L172.5 131.1zM467.5 380C411 436.5 319.5 436.5 263 380C213 330 206.5 251.2 247.6 193.7L248.7 192.1C258.1 177.8 278.1 174.4 293.3 184.7C307.7 194.1 311.1 214.1 300.8 229.3L299.7 230.9C276.8 262.1 280.4 306.9 308.3 334.8C339.7 366.2 390.8 366.2 422.3 334.8L534.5 222.5C566 191 566 139.1 534.5 108.5C506.7 80.63 462.7 76.99 430.7 99.9L429.1 101C414.7 111.3 394.7 107.1 384.5 93.58C374.2 79.2 377.5 59.21 391.9 48.94L393.5 47.82C451 6.731 529.8 13.25 579.8 63.24C636.3 119.7 636.3 211.3 579.8 267.7L467.5 380z"></path></svg>
            </a>
        </li>
    </ul>
</div>

svg イメージの代わりに自分で作成したカスタムイメージを挿入することもできます。 上記のコードをテーマファイルの適切な場所に追加します。 GeneratePress テーマを使用している場合、 ルックス » Elementsでフックを作成し、上記のコードを追加します。 次のように設定します。

  • Hook: generate_after_entry_title
  • Display Rulesの「投稿 - すべての投稿」に表示されるように設定

GeneratePress テーマのフックについては、次の記事を参照してください。

エレメンプロ プラグインや Avada などを使用している場合は、シングルポストテンプレートを作成して適切な場所に追加できます。

CSSコード

/* SNS 공유 */

.sns-go {
    margin-top: 30px;
}

.sns-go ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.sns-go li {
    float: left;
    margin-right: 10px;
}

.sns-go a {
    display: block;
    color: white;
    text-align: center;
    text-decoration: none;
    cursor: pointer;
}

/* 링크 복사 툴팁 */

.linktooltips-container{
background-color: #030303;
color: #ffffff;
padding: 5px 30px;
border-radius: 10px;
position: absolute;
z-index: 999;
}

適切に修正してご使用ください。 ルックス » カスタマイズ » 追加 CSS セクションに追加したり、 チャイルドテーマ 内の style.css ファイルに追加します。

リンクにアンダースコアが表示されるプロパティがソーシャル共有アイコンにも適用され、アンダースコア(_)がアイコンの間に表示される場合は、次のコードを追加して問題が解決するかどうかを確認してください。

.sns-go a {
    text-decoration: none !important;
}

JavaScriptコード

<script>
document.addEventListener('DOMContentLoaded', function() {
    
    // Social Share Links
    document.querySelector('.sns-go').addEventListener('click', function(e) {
        e.preventDefault();

        var shareLink = e.target.closest('.js-social-share');
        
        if (shareLink) {
            var shareUrl = shareLink.getAttribute('data-url') + encodeURIComponent(document.URL),
                shareTitle = shareLink.getAttribute('data-title') + encodeURIComponent(document.title);

            window.open(shareUrl + '&title=' + shareTitle, 'shareWindow', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
        }
    });

    // Copy to Clipboard Button
    document.querySelector('.js-copy-btn').addEventListener('click', function() {
        copyURL(this);
    });

    function copyURL(element) {
        let bodyClass = document.body.className;
        let match = bodyClass.match(/postid-(\d+)/);
        if (match) {
            let postId = match[1];
            let url = `https://www.thewordcracker.com/?p=${postId}`;
            navigator.clipboard.writeText(url).then(() => {
                element.insertAdjacentHTML('afterend', '<div class="linktooltips-container">URL이 복사되었습니다!</div>');
                setTimeout(() => { 
                    document.querySelectorAll('.linktooltips-container').forEach(el => el.remove()); 
                }, 3000);
            }).catch(error => {
                console.error('Copy failed', error);
                alert('URL 복사에 실패했습니다.');
            });
        } else {
            console.warn('Post ID not found');
            alert('URL을 생성할 수 없습니다.');
        }
    }
});
</script>

上記のコードでは、サイトドメインを適切に変更してください。 ティーストーリーブログにURLコピーボタンを追加したい場合組織にソーシャル共有ボタンとURLコピーボタンを追加する「に記載されているJavaScriptコードを使用できます。

ツールチップの代わりにアラート方式で「URLをコピーしました!」 通知を表示したい場合は、次のコードを使用できます。 以下のコードでは、jsコードを少し遅らせてロードするように少し修正しました。

<script>
document.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        setupSocialShare();
        setupCopyToClipboard();
    }, 2000); // 2-second delay
});

function setupSocialShare() {
    // Select the element to trigger the social sharing functionality
    const snsGo = document.querySelector('.sns-go');
    
    // If the element exists, attach an event listener to it
    snsGo && snsGo.addEventListener('click', (e) => {
        e.preventDefault();
        const shareLink = e.target.closest('.js-social-share');
        
        // If a valid share link is found, construct a URL and open a share window
        if (shareLink) {
            const shareUrl = `${shareLink.getAttribute('data-url')}${encodeURIComponent(document.URL)}`,
                  shareTitle = `${shareLink.getAttribute('data-title')}${encodeURIComponent(document.title)}`;

            window.open(`${shareUrl}&title=${shareTitle}`, 'shareWindow', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
        }
    });
}

function setupCopyToClipboard() {
    // Select the button intended to trigger the copy functionality
    const copyBtn = document.querySelector('.js-copy-btn');
    
    // If the button exists, attach an event listener to it
    copyBtn && copyBtn.addEventListener('click', (e) => {
        e.preventDefault();
        copyURLToClipboard(copyBtn);
    });
}

function copyURLToClipboard() {
    // Extract the post ID from the body's class attribute
    const bodyClass = document.body.className;
    const match = bodyClass.match(/postid-(\d+)/);

    // If a post ID is found, construct a URL and try to copy it to the clipboard
    if (match) {
        const postId = match[1];
        const url = `https://www.thewordcracker.com/?p=${postId}`;

        navigator.clipboard.writeText(url)
        .then(() => {
            // Inform the user that the URL was copied
            alert('URL이 복사되었습니다!');
        })
        .catch(error => {
            // If the copy fails, log the error and inform the user
            console.error('Copy failed', error);
            alert('URL 복사에 실패했습니다.'); 
        });
    }
}
</script>

JavaScriptコードは、次の記事を参照してロードすることが望ましいです。

上記の方法が難しいか面倒な場合 WPコードのようなプラグインをインストールし、フーター領域に上記のコードを追加するだけです。 この方法は便利ですが、あまりお勧めしません。

GeneratePress テーマを使用している場合は、新しいElementを追加してHookを作成し、上記のコードを入力してフックに "wp_footer"を指定します。 このブログではこの方法で適用しました。 同様に表示規則ですべての文を指定してください。

※上記のコードにエラーがある場合や改善事項がある場合は、コメントでお知らせいただきありがとうございます。

上記のコードが機能しない場合

上記のコードが機能しない場合は、次のコードを使用して動作するかどうかをテストしてください。次のコードはポストURLをそのままコピーします。 (上記のコードではhttps://example.com/?p={post_id}形式にコピーします。)

<script>
document.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        setupSocialShare();
        setupCopyToClipboard();
    }, 2000); // 2-second delay
});

function setupSocialShare() {
    // Select the element to trigger the social sharing functionality
    const snsGo = document.querySelector('.sns-go');
    
    // If the element exists, attach an event listener to it
    snsGo && snsGo.addEventListener('click', (e) => {
        e.preventDefault();
        const shareLink = e.target.closest('.js-social-share');
        
        // If a valid share link is found, construct a URL and open a share window
        if (shareLink) {
            const shareUrl = `${shareLink.getAttribute('data-url')}${encodeURIComponent(document.URL)}`,
                  shareTitle = `${shareLink.getAttribute('data-title')}${encodeURIComponent(document.title)}`;

            window.open(`${shareUrl}&title=${shareTitle}`, 'shareWindow', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
        }
    });
}

function setupCopyToClipboard() {
    // Select the button intended to trigger the copy functionality
    const copyBtn = document.querySelector('.js-copy-btn');
    
    // If the button exists, attach an event listener to it
    copyBtn && copyBtn.addEventListener('click', (e) => {
        e.preventDefault();
        copyURLToClipboard();
    });
}

function copyURLToClipboard() {
    // Use the current URL from the browser's address field
    const url = window.location.href;

    navigator.clipboard.writeText(url)
    .then(() => {
        // Inform the user that the URL was copied
        alert('URL copied to clipboard!');
    })
    .catch(error => {
        // If the copy fails, log the error and inform the user
        console.error('Copy failed', error);
        alert('Failed to copy URL.'); 
    });
}
</script>

JSファイルロードの例

上記のアラート方式でURLをコピーするJavaScriptをロードしたい場合は、次の手順に進みます。

1. この Naver カフェの投稿からjsファイルをダウンロードしてください。

2. jsファイルをテキストエディタで開き、https://www.thewordcracker.com部分をそのサイトのURLに置き換えます。

3. FTP / SFTPを介してチャイルドテーマ内のjsフォルダ(例:/public_html/wp-content/themes/generatepress-child/js) としてアップロードします。

4.次のコードをチャイルドテーマ内の関数ファイル(functions.php)に追加します。

function my_theme_enqueue_scripts() {
    if (is_single()) {
        // Correctly register the script
        wp_register_script('my-copytext-script', get_stylesheet_directory_uri() . '/js/copytext.js', array('jquery'), '', true);

        // Conditionally enqueue the script
        wp_enqueue_script('my-copytext-script');
    }
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

これにはFTP接続が必要です。

チャイルドテーマ(子テーマ)を作成して作業してください。詳しくは Naver カフェの投稿を参照してみてください。

参照


17のコメント

コメント

  1. こんにちは。
    他のSNS共有はうまく機能しますが、URLだけがURLを生成できないというポップアップが表示されるようにどのような部分を変更する必要がありますか?

    応答
    • このサイトでは、アラート方式のJavaScriptコードを追加しました。このサイトではうまく動作しているようです。もしかしたら動作しませんか? (ブラウザでジャスが無効になると機能しません。)

      JavaScriptコードを正しく追加したことを確認してください。場合によっては、キャッシュプラグインや最適化プラグインが原因で、Jusが正しく機能しないことがあります。加えて、bodyタグにpost idが追加されているかどうかをチェックしてください。

      応答
      • 親切な回答ありがとうございます。

        提供していただいたhtml、java scriptを適用しましたが、キャッシュプラグインのインストール以降URLがなかったようです。キャッシュプラグインを無効にしてもURLだけは適用されません。

        JavaScriptコードはファイルの読み込みが難しく、Astra hookプラグインでWP_footerを適用しました。 JavaScriptコードでURLだけを自分のサイトアドレスに変更しましたが、post idも別に追加する必要がありますか?

      • 動作しない正確な理由はわかりません。同様のコードをティーストーリーブログにも適用しています。

        https://avada.tistory.com/3272

        エラーログがある場合は、お知らせください。原因を特定するのに役立ちます。

      • こんにちは、「上記のコードが機能しない場合」セクションに記載されているコードでテストしてみますか?

      • 「上記のコードが機能しない場合」コードに入れるとうまくいきます。親切な回答ありがとうございます。

        キャッシュプラグインを有効にして突然コードが適用されなくなりましたが、私はAstra Hookプラグインを使ってクラッシュしますか?どちらか一つを選ぶべきかどうか疑問に思います。

      • キャッシュプラグインの設定を調整してください。 JavaScriptが読み込まれないようにする設定があります。

      • やり直してみると、最初の上段のみが適用され、下段からはURLは適用されません。私はエラーコードを見ることができませんが、私のサイトアドレスを残してもいいですか?この住所部分のみを削除してコメント公開が可能かどうかお問い合わせください。迷惑をかけて申し訳ありません。 ㅠ

    • 「JSファイルのロード例」部分を追加しました。参照してJSファイルをロードしてください。うまくいかない場合は、エラーメッセージを教えてください。

      応答
    • CSSスタイルが適用されていないようですね。 CSSコードも追加しますか? 子テーマを作成したら、子テーマ内のstyle.cssファイルに本文に示されているCSSコードを追加できます。

      応答