이 워드프레스 블로그에 사용된 SNS 공유 버튼 & URL 복사 버튼

Last Updated: 2024년 02월 04일 | | 17개 댓글

이 워드프레스 블로그에는 플러그인을 사용하지 않고 직접 코드를 만들어 네이버, 페이스북, 트위터 공유 버튼과 URL 복사 버튼을 추가하여 사용하고 있습니다. 보다 쉽게 코드를 관리가 가능하고 일관성을 가지도록 코드를 최근 업데이트했습니다.

네이버 카페에서 이 블로그에 사용된 URL 복사 버튼을 구현하는 방법에 대하여 문의하신 분이 계셔서 이 사이트에 사용된 SNS 공유 버튼 & URL 복사 버튼의 코드를 아래에 정리해 보았습니다.

[ 이 글은 2024년 2월 4일에 마지막으로 업데이트되었습니다. ]

이 워드프레스 블로그에 사용된 SNS 공유 버튼 & URL 복사 버튼

이 워드프레스 블로그에 사용된 SNS 공유 버튼 & URL 복사 버튼

현재 이 블로그에는 네이버, 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="네이버에 공유" 
                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="페이스북에 공유" 
        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="트위터에 공유" 
        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)를 생성한 다음, 위의 코드를 추가합니다. 다음 같이 설정합니다.

  • Hook: generate_after_entry_title
  • Display Rules에서 "글 - All 글"에 표시되도록 설정

GeneratePress 테마의 후크에 대해서는 다음 글을 참고해보세요.

엘리멘터 프로 플러그인이나 아바다 테마 등을 사용하는 경우 Single Post 템플릿을 만들어서 적절한 곳에 추가할 수 있습니다.

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;
}

자바스크립트 코드

<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 복사 버튼 추가하기"에 제시된 자바스크립트 코드를 사용할 수 있습니다.

툴팁 대신 alert 방식으로 "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 코드는 다음 글을 참고하여 로드하는 것이 바람직합니다.

위의 방법이 어렵거나 번거로운 경우 WPCode와 같은 플러그인을 설치하고 푸터(Footer) 영역에 상기 코드를 추가하면 됩니다. 이 방법은 편리하지만 그다지 권장하지는 않습니다.

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 파일 로드 예시

상기의 alert 방식으로 URL을 복사하는 자바스크립트를 로드하고 싶은 경우 다음과 같은 과정으로 진행할 수 있습니다.

1. 이 네이버 카페 글에서 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 접속이 가능해야 합니다.

차일드 테마(자식 테마)를 만들어서 작업하세요. 자세한 내용은 네이버 카페 글을 참고해보세요.

참고


17 개 댓글

Leave a Comment

  1. 안녕하세요.
    다른 SNS 공유는 잘 작동이 되는데, URL만 URL을 생성할 수 없다는 팝업이 뜨는 데 어떤 부분을 수정해야할까요?

    응답
    • 이 사이트에서는 alert 방식의 자바스크립트 코드를 추가했습니다. 이 사이트에서는 잘 작동하는 것 같은데요. 혹시 작동하지 않나요? (브라우저에서 자스가 비활성화되면 작동하지 않을 것입니다.)

      자바스크립트 코드를 올바르게 추가했는지 확인해보시기 바랍니다. 경우에 따라 캐시 플러그인이나 최적화 플러그인 때문에 자스가 제대로 작동하지 않을 수도 있습니다. 이외에 body 태그에 post id가 추가되어 있는지도 체크해보세요.

      응답
      • 친절한 답변 감사합니다.

        제공해 주신 html, java script 적용했는데, 캐시 플러그인 설치 이후 URL 이 안되었던것 같습니다. 캐시 플러그인을 비활성화 했는데도 URL만 적용이 되지 않습니다.

        자바스크립트 코드를 파일 로드가 어려워서 아스트라 hook 플러그인에서 WP_footer 적용했습니다. 자바스크립트 코드에서 URL만 제 사이트 주소로 변경했는데, post id도 따로 추가해야할 것이 있을까요?

      • "상기 코드가 작동하지 않는 경우" 코드로 넣으니 잘 됩니다. 친절한 답변 너무 감사합니다.

        캐시 플러그인을 활성화해서 갑자기 코드가 적용이 안되었는데, 제가 아스트라 훅 플러그인을 써서 충돌이 나는건가요? 둘 중에 하나만 선택해야하는지 궁금합니다.

      • 다시 해보니, 첫 상단 글만 적용이 되고 아래글 부터는 URL이 적용되지 않습니다. 제가 에러 코드를 볼 줄 모르는데, 제 사이트 주소를 남겨 드려도 될까요? 이 주소부분만 삭제하고 댓글 노출이 가능하신지 문의드립니다. 귀찮게 해서 죄송합니다. ㅠ

    • "JS 파일 로드 예시" 부분을 추가했습니다. 참고하여 JS 파일을 로드해보시기 바랍니다. 잘 안 되는 경우 에러 메시지를 알려주시기 바랍니다.

      응답
    • CSS 스타일이 적용되지 않은 것 같네요. CSS 코드도 추가해보시겠어요? 자식 테마를 만들었다면 자식 테마 내의 style.css 파일에 본문에 제시된 CSS 코드를 추가할 수 있습니다.

      응답