워드프레스에서 글을 작성하다보면, URL링크를 참조로 입력하는 경우가 꽤 있다.

이런 경우 해당 URL 을 cURL로 파싱하여 썸네일과 컨텐츠 내용 일부를 미리보기로 보여주는 것이 보는 사람이

링크를 클릭할 것인가 말 것인가를 판단하기에 좋은 정보가 될 수 있다.

워드프레스 테마의 functions.php 에 아래 코드를 추가하거나 코드 스니펫 플러그인을 이용하여 코드를 스니펫 형태로 만들어놓고 숏코드 형태로 쓸 수 있다.

function fetch_url_metadata_with_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $html = curl_exec($ch);
    curl_close($ch);

    // 메타데이터 파싱 로직
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $nodes = $doc->getElementsByTagName('meta');
    $title = $description = $image = '';

    foreach ($nodes as $node) {
        if($node->getAttribute('property') == 'og:title') {
            $title = $node->getAttribute('content');
        }
        if($node->getAttribute('property') == 'og:description') {
            $description = $node->getAttribute('content');
            // 설명을 100자로 자릅니다.
            $description = mb_substr($description, 0, 100, 'UTF-8');
        }
        if($node->getAttribute('property') == 'og:image') {
            $image = $node->getAttribute('content');
        }
    }

    if (empty($title)) {
        $nodes = $doc->getElementsByTagName('title');
        $title = $nodes->item(0)->nodeValue;
    }

    return array(
        'title' => $title,
        'description' => $description,
        'image' => $image
    );
}

function create_url_preview_shortcode($atts) {
    $a = shortcode_atts(array('url' => ''), $atts);
    $metadata = fetch_url_metadata_with_curl($a['url']);

    $output = '<a href="'. esc_url($a['url']) .'" target="_blank">';
    $output .= '<div style="border: 1px solid #ccc; padding: 10px; margin: 10px 0;">';
    $output .= '<h3>'. esc_html($metadata['title']) .'</h3>';
    $output .= '<p>'. esc_html($metadata['description']) .'</p>';
    $output .= '<img src="'. esc_url($metadata['image']) .'" alt="Thumbnail">';
    $output .= '</div></a>';

    return $output;
}
add_shortcode('url_preview', 'create_url_preview_shortcode');

[ url_preview url=”링크주소“ ] 를 입력하면 알아서 컨텐츠를 파싱하여 보여주게 된다.

#워드프레스 #소스코드 #파싱 #컨텐츠미리보기

Author: 모요
댓글

댓글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

*

©2024 MOYO Blog with DAON Consulting Co,LTD.

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

보내는 중입니다..

로그인하세요.

계정 내용을 잊으셨나요 ?