最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp get archives - wp_get_archives() - Get CSS selector for current month

programmeradmin8浏览0评论

I'm looking for how to get a class in the wp_get_archives functions to get the current month (when we are in a month archive) just like when we call wp_list_categories, the current category has a ".current-cat" selector for CSS or when we call wp_list_pages we have a '.current_page_item' selector.

I'm looking for how to get a class in the wp_get_archives functions to get the current month (when we are in a month archive) just like when we call wp_list_categories, the current category has a ".current-cat" selector for CSS or when we call wp_list_pages we have a '.current_page_item' selector.

Share Improve this question asked Aug 21, 2012 at 12:41 Fredy31Fredy31 8782 gold badges16 silver badges31 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 4

Put the following function in your functions.php

function wpse_62509_current_month_selector( $link_html ) {
    $current_month = date("F Y");
    if ( preg_match('/'.$current_month.'/i', $link_html ) )
        $link_html = preg_replace('/<li>/i', '<li class="current-month">', $link_html );
    return $link_html;
}

And then add the following line just before calling wp_get_archives()

add_filter( 'get_archives_link', 'wpse_62509_current_month_selector' );

You might also want to remove the filter after calling wp_get_archives() so that it doesn't mess with other wp_get_archives() or get_archives_link() function calls.

remove_filter( 'get_archives_link', 'wpse_62509_current_month_selector' );

This function was created with the great help of Joshua Abenazer. Thanks! Basically, if is a monthly archive, go and get the current month watched, and add a class on the li. Worked great.

function wpse_62509_current_month_selector( $link_html ) {
    if (is_month()){
        $current_month = get_the_date("F Y");
        if ( preg_match('/'.$current_month.'/i', $link_html ) )
            $link_html = preg_replace('/<li>/i', '<li class="current-month">', $link_html );
    }
    return $link_html;
}

add_filter( 'get_archives_link', 'wpse_62509_current_month_selector' );

As of WordPress 5.3, <a> elements generated by wp_get_archives (etc) for links to the current page have the attribute aria-current="page" added to them. If you just want to style the current page link differently, you can now target this with CSS, assuming you are happy for the styles to all be on the <a>:

a[aria-current="page"] {
color: red;
}

…or even just:

a[aria-current] {
color: red;
}
发布评论

评论列表(0)

  1. 暂无评论