钩子文档

get_archives_link

💡 云策文档标注

概述

get_archives_link 是一个 WordPress 过滤器,用于修改归档链接的 HTML 内容。它允许开发者自定义链接的显示方式,例如添加 CSS 类或调整格式。

关键要点

  • 过滤器名称:get_archives_link,用于过滤归档链接的 HTML 内容。
  • 参数:包括 $link_html(链接 HTML)、$url(URL)、$text(文本描述)、$format(格式)、$before(前置内容)、$after(后置内容)和 $selected(是否选中)。
  • 用途:常用于动态添加类或修改链接,以增强前端交互性,如高亮当前归档页面。
  • 版本历史:从 WordPress 2.6.0 引入,5.2.0 添加 $selected 参数,4.5.0 添加多个参数。

代码示例

function example_get_archives_link($link_html) {
    if (is_day() || is_month() || is_year()) {
        if (is_day()) {
            $data = get_the_time('Y/m/d');
        } elseif (is_month()) {
            $data = get_the_time('Y/m');
        } elseif (is_year()) {
            $data = get_the_time('Y');
        }

        // Link to archive page
        $link = home_url($data);

        // Check if the link is in string
        $strpos = strpos($link_html, $link);

        // Add class if link has been found
        if ($strpos !== false) {
            $link_html = str_replace('<a', '<a class="current-archive"', $link_html);
        }
    }

    return $link_html;
}
add_filter("get_archives_link", "example_get_archives_link");

注意事项

  • 使用此过滤器时,需确保正确处理参数,避免破坏链接结构。
  • 示例代码展示了如何根据当前页面类型添加 current-archive 类,类似 wp_list_categories() 中的 current-cat 功能。

📄 原文内容

Filters the archive link content.

Parameters

$link_htmlstring
The archive HTML link content.
$urlstring
URL to archive.
$textstring
Archive text description.
$formatstring
Link format. Can be 'link', 'option', 'html', or custom.
$beforestring
Content to prepend to the description.
$afterstring
Content to append to the description.
$selectedbool
True if the current page is the selected archive.

Source

return apply_filters( 'get_archives_link', $link_html, $url, $text, $format, $before, $after, $selected );

Changelog

Version Description
5.2.0 Added the $selected parameter.
4.5.0 Added the $url, $text, $format, $before, and $after parameters.
2.6.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can use this filter to add current-archive class to element (as current-cat in wp_list_categories() function):

    function example_get_archives_link($link_html) {
        if (is_day() || is_month() || is_year()) {
            if (is_day()) {
                $data = get_the_time('Y/m/d');
            } elseif (is_month()) {
                $data = get_the_time('Y/m');
            } elseif (is_year()) {
                $data = get_the_time('Y');
            }
    
            // Link to archive page
            $link = home_url($data);
    
            // Check if the link is in string
            $strpos = strpos($link_html, $link);
    
            // Add class if link has been found
            if ($strpos !== false) {
                $link_html = str_replace('<li>', '<li class="current-archive">', $link_html);
            }
        }
    
        return $link_html;
    }
    add_filter("get_archives_link", "example_get_archives_link");