MOYOMOYO
모요 · PERSONAL BLOG

MOYO

생각과 경험을 기록하는 공간입니다.

← 글 목록

URL링크로 컨텐츠 미리보기 파싱하기

모요조회 4댓글 0

워드프레스에서 글을 작성하다보면, 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="링크주소“ ] 를 입력하면 알아서 컨텐츠를 파싱하여 보여주게 된다.

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

로그인 후 좋아요

댓글 0

등록된 댓글이 없습니다.