简体   繁体   中英

Add active class to custom post type date archive

I'm using a plugin to create custom post type date archives by year:

<?php 
    $args = array(
        'post_type' => 'unistused',
        'type' => 'yearly',
        'format' => 'anchor',
        );
    cptda_get_archives($args); 
?>

I've also generated a custom format for the permalink so it would anchor to the correct section when clicking the yearly archive:

//
add_filter ('get_archives_link',
function ($link_html, $url, $text, $format, $before, $after) {
    if ('anchor' == $format) {
        $link_html = "<li class='year-archive'><a href='$url#dreams'>"
                   . "$text"
                   . '</a></li>';
    }
    return $link_html;
}, 10, 6);

Unfortunately the custom structure 'anchor' does not add the 'active' class to the permalink structure when a archive page is viewed and I'm unable to implement a solution or experiment to achieve this. Any help would be appreciated.

You probably need to add it yourself in this custom function:

add_filter ('get_archives_link',
function ($link_html, $url, $text, $format, $before, $after) {
    if ('anchor' == $format) {
        
        global $wp;
        $current_url = home_url( add_query_arg( array(), $wp->request ) );

        $active_classname =  $current_url === $url ? 'active' : '';

        $link_html = "<li class=\"year-archive\"><a href=\"$url#dreams\" class=\"$active_classname\">$text</a></li>";
    }
    return $link_html;
}, 10, 6);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM