폴리랑에 유용한 5가지 스니펫

Publicado: 05/02/2025 : 18:29 | Actualizado: 05/02/2025 : 19:10 |

No comments

 

폴리랑에 유용한 5가지 스니펫 0
2025년 2월 5일 캡처

다국어 블로그를 만드는 데 가장 적합한 플러그인에 대한 의견이 다양하고 첫 번째 버전 이후 모두 작업을 단순화하고 용이하게 하는 등 많이 발전했지만, 가장 많이 사용되는 플러그인 중 하나는 Polylang입니다.

현재까지 70만 건 이상의 설치가 이루어진 이 앱은 여전히 가장 가볍고 효과적인 옵션 중 하나입니다.

다음은 언젠가 유용할 수 있는 기능과 필터가 포함된 작은 스니펫 목록입니다. 이 모든 기능은 Polylang 무료 버전에서 작동하며 여기에서 테스트 및/또는 사용되었습니다.

무료 버전에서 Polylang을 사용하여 원본 게시물의 콘텐츠를 복사합니다.

워드프레스용 Polylang 플러그인의 무료 버전을 사용하는 경우 번역을 위해 생성되는 새 페이지 또는 글이 원본 콘텐츠를 복사하지 않는다는 것을 이미 알고 있을 것입니다. 이것은 유료 버전의 기능 중 하나이며 무료 버전에서는 콘텐츠를 직접 붙여넣어야 합니다.

이 문제를 해결하고 프로세스 속도를 높이려면 템플릿의 functions.php 파일에 이러한 함수를 추가하면 됩니다. 이제 새 번역을 추가하면 복사된 원본 콘텐츠(제목 및 내용)와 함께 열립니다.

// Copying content when creating a translation with Polylang
function jb_editor_content( $content ) {
// Polylang sets the 'from_post' parameter
    if ( isset( $_GET['from_post'] ) ) {
        $my_post = get_post( $_GET['from_post'] );
        if ( $my_post )
            return $my_post->post_content;
    }
    return $content;
}
add_filter( 'default_content', 'jb_editor_content' );
// Copy title when creating a translation with Polylang
function jb_editor_title( $title ) {
// Polylang sets the 'from_post' parameter
    if ( isset( $_GET['from_post'] ) ) {
        $my_post = get_post( $_GET['from_post'] );
        if ( $my_post )
            return $my_post->post_title;
    }
    return $title;
}
add_filter( 'default_title', 'jb_editor_title' );

* 코드 조각은 2020년 12월의 노트에서 발견되었습니다. 아직은 작동하지만, 시간이 지나고 향후 폴리랑 업데이트가 있을 때 실패할 경우를 대비해 계속 주시하는 것도 나쁘지 않을 것입니다.

각 언어에서 Polylang으로 번역된 총 게시물 수를 표시합니다.

이 기능을 사용하면 각 언어에 대한 쇼트코드를 추가하여 Polylang 플러그인으로 번역이 추가된 언어로 게시된 총 글 수를 표시할 수 있습니다.

이 기능은 내 통계 페이지에서 테스트를 거쳐 제대로 작동하며 자동으로 업데이트되는 카운터 목록을 유지하는 데 유용합니다.

스니펫은 템플릿의 functions.php에 추가됩니다:

// Function to display number of published posts by language for Polylang
function polylang_post_count_by_language($atts) {
    // Atributos del shortcode
    $atts = shortcode_atts(array(
        'lang' => '', // Código de idioma (ej: 'es', 'en', etc.)
    ), $atts, 'post_count_by_lang');

    // Check if Polylang is active
    if (!function_exists('pll_languages_list')) {
        return 'Polylang plugin is not active.';
    }

    // Get the language code
    $lang = $atts['lang'];
    if (empty($lang)) {
        return 'Language code is required.';
    }

    // Single key for transient
    $transient_key = 'post_count_by_lang_' . $lang;

    // Trying to get the count from the cache
    $post_count = get_transient($transient_key);

    // If there is no cache, perform the query
    if (false === $post_count) {
        // Configure the query to count posts by language
        $args = array(
            'lang'        => $lang,
            'post_type'   => 'post', // Type of post (you can change it if necessary)
            'post_status' => 'publish', // Only published posts
            'fields'      => 'ids', // Only obtain IDs to reduce the burden
            'numberposts' => -1, // All posts
        );

        // Make an enquiry
        $query = new WP_Query($args);

        // Get the total number of posts
        $post_count = $query->found_posts;

        // Cache for 12 hours (43200 seconds)
        set_transient($transient_key, $post_count, 43200);
    }

    // Return the number of posts
    return $post_count;
}
add_shortcode('post_count_by_lang', 'polylang_post_count_by_language');

여기서 직면하는 문제 중 하나는 이 블로그의 경우처럼 사이트에 여러 언어로 된 글이 많은 경우 데이터베이스 쿼리의 영향으로 로딩 속도가 느려질 수 있다는 것입니다. 이 코드는 이 점을 고려하여 전체 글 개체를 로드하지 않음으로써 메모리 오버헤드를 줄이기 위해 필드 => 'ids '가 포함된 WP_Query를 사용하여 쿼리를 최적화했습니다.

글 수는 set_transient를 사용하여 저장되며 반복적인 데이터베이스 쿼리를 피할 수 있습니다. 이 예에서는 캐시가 12시간마다 업데이트되며 초 단위로 표시됩니다(필요에 따라 이 시간을 조정할 수 있음).

쿼리를 최적화하기 위해 모든 객체를 로드할 필요 없이 총 글 수를 반환하는 found_posts에 액세스하기 위해 get_posts 대신 WP_Query를 사용합니다.

fields => 'ids' 매개변수는 글 ID만 검색하여 메모리 부하를 줄입니다.

어느 시점에서 캐시를 수동으로 지워야 하는 경우(예: 새 글을 게시한 후) 오래된 데이터를 표시하지 않도록 캐시를 지워야 하는 경우 사용할 수 있습니다:

delete_transient('post_count_by_lang_' . $lang);

이 프로세스를 자동화하려면 글이 게시, 업데이트 또는 삭제될 때마다 다음 함수를 사용하여 일시적으로 삭제할 수 있습니다. 템플릿의 functions.php에 이 함수를 추가하면 이러한 모든 작업에 대해 후크가 활성화됩니다:

//Deleting the transient when publishing, updating or deleting a post
function clear_post_count_transient($post_id) {
    // Check if the post is of type 'post' (or the type you are counting).
    if (get_post_type($post_id) === 'post') {
        // Get the language of the post using Polylang
        if (function_exists('pll_get_post_language')) {
            $lang = pll_get_post_language($post_id);
            
            // If the language is obtained, delete the corresponding transient.
            if ($lang) {
                delete_transient('post_count_by_lang_' . $lang);
            }
        }
    }
}
add_action('save_post', 'clear_post_count_transient'); // When publishing or updating
add_action('delete_post', 'clear_post_count_transient'); // By deleting

그리고 위의 시나리오를 포함하여 여러 가지 가능한 시나리오에 따라 캐시를 자동으로 지웁니다:

// Function to delete the transient when necessary
function clear_post_count_transient($post_id) {
    if (get_post_type($post_id) === 'post') {
        if (function_exists('pll_get_post_language')) {
            $lang = pll_get_post_language($post_id);
            if ($lang) {
                delete_transient('post_count_by_lang_' . $lang);
            }
        }
    }
}
add_action('save_post', 'clear_post_count_transient');
add_action('delete_post', 'clear_post_count_transient');

//Function to delete transient when changing the language of a post
function clear_post_count_transient_on_language_change($post_id, $lang) {
    $old_lang = pll_get_post_language($post_id);
    if ($old_lang) {
        delete_transient('post_count_by_lang_' . $old_lang);
    }
    if ($lang) {
        delete_transient('post_count_by_lang_' . $lang);
    }
}
add_action('pll_save_post', 'clear_post_count_transient_on_language_change', 10, 2);

// Function to delete all transients when uninstalling or deactivating Polylang
function clear_all_post_count_transients() {
    if (function_exists('pll_languages_list')) {
        $languages = pll_languages_list();
        foreach ($languages as $lang) {
            delete_transient('post_count_by_lang_' . $lang);
        }
    }
}
register_deactivation_hook(__FILE__, 'clear_all_post_count_transients');
register_uninstall_hook(__FILE__, 'clear_all_post_count_transients');

숫자를 표시하려는 위치에 해당 코드와 함께 각 언어의 단축 코드를 사용하여 숫자를 표시합니다. 다음과 같이 표시됩니다:

For Spanish: [post_count_by_lang lang="es"]
For English: [post_count_by_lang lang="en"]
For German: [post_count_by_lang lang="de"]
For French: [post_count_by_lang lang="fr"]
etc.

다른 유형의 콘텐츠(페이지, 사용자 정의 글 유형 등)를 계산하려면 코드에서'post_type'을 수정할 수 있습니다.

이 URL에는 단축 코드가 작동하는 예가 나와 있습니다.

모든 페이지 또는 게시물에 기본 폴리랑 배너 추가하기

Polylang에는 .png로 된 249개의 16x11 플래그 컬렉션이 포함되어 있으므로 HTML이나 CSS를 작성할 필요 없이 목록을 꾸미고 표, 단락 등에 추가하는 데 사용할 수 있습니다.

이 기능을 사용하면 단축 코드를 통해 플러그인에서 사용하는 기본 배너의 이미지를 추가할 수 있습니다.

이를 사용하려면 하위 테마의 functions.php, 사용자 정의 플러그인 또는 코드 스니펫을 사용하는 경우 코드 스니펫을 추가하면 됩니다.

function polylang_flag_shortcode($atts) {
    // Shortcode attributes
    $atts = shortcode_atts(array(
        'code' => '', // Flag code (e.g. 'es', 'en', 'fr')
        'size' => '16', // Flag size (width in pixels)
    ), $atts, 'polylang_flag');

    // Check if a flag code was provided
    if (empty($atts['code'])) {
        return 'Flag code not provided.';
    }

    // Polylang flag base route
    $flag_path = plugins_url('polylang/flags/' . $atts['code'] . '.png');

    // Create the HTML of the flag image
    $flag_html = '<img src="' . esc_url($flag_path) . '" alt="' . esc_attr($atts['code']) . '" width="' . esc_attr($atts['size']) . '" height="auto" />';

    return $flag_html;
}
add_shortcode('polylang_flag', 'polylang_flag_shortcode');

코드를 추가한 후에는 해당 국가 코드와 함께 쇼트코드를 워드프레스 페이지 또는 글에 사용할 수 있으며 /wp-content/plugins/polylang/flags/ 폴더의 플래그 파일 이름과 정확히 일치하는지 확인합니다.

[polylang_flag code="en" size="32"]
[polylang_flag code="fr" size="24"]

//Original size
[polylang_flag code="de"]

플래그의 크기를 조정하려면 쇼트코드에서 크기 속성 값을 변경하기만 하면 됩니다.

나만의 배너를 만들어 사용하거나 다른 디자인의 다른 컬렉션을 사용하려면 새 배너를 다른 이름의 새 폴더에 호스팅하고(그렇지 않으면 플러그인이 업데이트될 때 변경 사항을 잃게 됩니다) 코드에 새 경로를 추가하면 됩니다. 예를 들어

$flag_path = plugins_url('polylang/nuevas_banderas/' . $atts['code'] . '.png');

언어 선택기 옆에 SVG 아이콘 추가하기

이 스니펫은 Polylang의 모국어 선택기 왼쪽에 '번역' 기호가 있는 SVG 아이콘을 추가하여 시각적으로 더 매력적이고 방문자의 시선을 사로잡을 수 있도록 합니다. 예시에서 아이콘은 이 블로그에서 사용하는 아이콘입니다. 가장 마음에 드는 아이콘을 찾아서 교체할 수 있습니다. 다음은 그 중 몇 가지입니다.

function polylang_add_translate_icon($output) {
    //SVG icon for "translate".
    $translate_icon = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 5px;"><path d="M24 24h-2.784l-1.07-3h-4.875l-1.077 3h-2.697l4.941-13h2.604l4.958 13zm-4.573-5.069l-1.705-4.903-1.712 4.903h3.417zm-9.252-12.804c.126-.486.201-.852.271-1.212l-2.199-.428c-.036.185-.102.533-.22 1-.742-.109-1.532-.122-2.332-.041.019-.537.052-1.063.098-1.569h2.456v-2.083h-2.161c.106-.531.198-.849.288-1.149l-2.147-.645c-.158.526-.29 1.042-.422 1.794h-2.451v2.083h2.184c-.058.673-.093 1.371-.103 2.077-2.413.886-3.437 2.575-3.437 4.107 0 1.809 1.427 3.399 3.684 3.194 2.802-.255 4.673-2.371 5.77-4.974 1.134.654 1.608 1.753 1.181 2.771-.396.941-1.561 1.838-3.785 1.792v2.242c2.469.038 4.898-.899 5.85-3.166.93-2.214-.132-4.635-2.525-5.793zm-2.892 1.531c-.349.774-.809 1.544-1.395 2.15-.09-.646-.151-1.353-.184-2.108.533-.07 1.072-.083 1.579-.042zm-3.788.724c.062.947.169 1.818.317 2.596-1.996.365-2.076-1.603-.317-2.596zm11.236-1.745l-2.075-5.533 5.414-1.104-.976 1.868c2.999 2.418 4.116 5.645 4.532 8.132-1.736-2.913-3.826-4.478-5.885-5.321l-1.01 1.958zm-7.895 10.781l1.985 5.566-5.43 1.016 1.006-1.852c-2.96-2.465-4.021-5.654-4.397-8.148 1.689 2.94 3.749 4.483 5.794 5.36l1.042-1.942zm10.795-6.029"/></svg>';

    // Add the icon before the selector
    return $translate_icon . '<span style="margin-left: 5px;">' . $output . '</span>';
}
add_filter('pll_the_languages', 'polylang_add_translate_icon');


외국어 버전의 존재에 대한 사용자 지정 가능한 경고 표시

이 기능은 글이나 페이지의 어느 곳에나 추가할 수 있는 노란색 배경의 경고를 표시하는 단축 코드를 생성합니다. 이 메시지는 해당 글에 Polylang을 사용한 영어 번역이 있음을 경고하고 영어 버전으로 연결되는 링크를 제공합니다.

이 예시를 선택한 이유는 어떤 언어로 작성된 기사가 영어권 국가와 영어 브라우저에서 더 많은 트래픽을 받았을 때 이 방법을 사용했기 때문입니다(이 경우에도 작성자가 영어 버전을 찾고 있었다고 보장할 수는 없습니다). 하지만 어떤 경우에는 방문자 리텐션을 보장할 수 있는 방법입니다.

functions.php에 추가할 코드

  // English version notice
function polylang_translation_notice_shortcode() {
    // Verifica si el plugin Polylang está activo
    if (!function_exists('pll_the_languages')) {
        return '';
    }

    // Get the ID of the current post
    $post_id = get_the_ID();

    // Get the English translation of the current post
    $english_post_id = pll_get_post($post_id, 'en'); // 'en' es el código del idioma inglés

    // Si no hay una traducción en inglés, no mostrará nada
    if (!$english_post_id) {
        return '';
    }

    // Get the link to the English version
    $english_post_url = get_permalink($english_post_id);

    // Crear el contenido del aviso
    $ticker_content = sprintf(
        '<div style="background-color: #ffffcc; padding: 10px; border-radius: 5px; margin-bottom: 20px; font-size: 14px;">
            This article has an English version. <a href="%s" style="color: #0073e6; text-decoration: none; font-weight: bold;">Read</a>
        </div>',
        esc_url($english_post_url)
    );

    return $ticker_content;
}
add_shortcode('polylang_translation_notice', 'polylang_translation_notice_shortcode');

스타일에서는 메시지, 텍스트 크기, 텍스트 색상, 배경 및 링크를 원하는 대로 수정할 수 있습니다.

원하는 위치에 메시지를 추가하려면 이 단축 코드를 사용하면 됩니다:

[polylang_translation_notice]

예제의 CSS를 사용하면 다음과 같이 표시됩니다.

연한 노란색 배경에 14px 검은색 텍스트와 파란색 링크가 있는 광고의 예시입니다.

다른 언어로 번역된 글에 알림을 추가하려면 pll_get_post($post_id, 'en'); 의 언어 코드를 'fr', 'de', 'it' 등으로 변경하면 됩니다. 여러 개의 글을 사용해야 하는 경우 언어별로 각각 다른 스니펫을 추가할 수 있습니다. 하나의 스니펫에 모두 추가할 수도 있지만 저는 하나만 필요했습니다.


Suscríbete por email para recibir las viñetas y los artículos completos y sin publicidad

관련 문서

Leave a Comment

이메일 구독

기사가 게시되는 즉시 광고 없이 받은 편지함에서 전체 기사를 무료로 받아보세요. 피드의 전체 콘텐츠는 외부 서비스를 통해 광고 없이 전송됩니다.