Polylang 的五个实用片段

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

No comments

 

Polylang 的五个实用片段 0
2025 年 2 月 5 日捕获

虽然关于哪种插件是创建多语言博客的最佳选择众说纷纭,而且所有这些插件自其最初版本以来都有了很大的发展,简化和促进了任务的完成,但最常用的插件之一是Polylang

迄今为止,它的有效安装次数已超过 70 万次,仍然是最轻便、最有效的选择之一。

这里是一个小的功能和过滤器片段 列表,可能在某些时候会有用。所有这些都适用于免费版 Polylang,并已在此进行过测试和/或使用。

使用免费版 Polylang 复制原帖内容

如果您使用免费版的 WordPressPolylang插件,您就会知道它生成的新页面或帖子翻译内容不会复制原始内容。这是其付费版本的功能之一,而在免费版本中,您必须手动粘贴内容。

要解决这个问题并加快进程,只需在模板的 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' );

*Thissnippet是在 2020 年 12 月的一份说明中发现的。虽然它仍然有效,但如果随着时间的推移和未来 Polylang 的更新,它可能会失效。

显示每种语言中使用 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 小时更新一次,单位为秒(可根据需要调整)。

为了优化查询,使用WP_Query代替get_posts访问found_posts,这样就可以返回帖子总数,而无需加载所有对象。

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 横幅广告

由于 Polylang 包含249 个.png 格式的16x11标志集合,我们可以使用它们来装饰列表,将它们添加到表格、 段落等,而无需编写 HTML 或 CSS。

此功能允许您通过简码添加插件使用的任何原生横幅的图像。

要使它们可用,您可以在子主题的functions.php中、自定义插件中或使用Code Snippet(如果您使用它)添加片段。

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');

添加代码后,您就可以在任何 WordPress 页面或文章中使用带有相应国家代码的简码,确保与 /wp-content/plugins/polylang/flags/文件夹中的国旗文件名完全一致

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

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

要调整旗帜的大小,只需更改简码中大小属性的值即可。

如果您想创建和使用自己的横幅,或拥有另一个不同设计的系列,只需将新横幅(.png 格式)放在一个新文件夹中,并使用不同的名称(否则插件更新时将丢失更改),然后将新路径添加到代码中即可。例如

$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

相关文章

发表评论

透過電子郵件訂閱

在文章發表後,立即在您的收件匣中免費接收無廣告的完整文章。 饋送的完整內容透過外部服務免廣告傳送。