joli_toc_item_link_attributes

Since v2.1.2

Add custom HTML attributes to the TOC headings. If the rel=”nofollow” option is activated, $attrs[‘rel’] will be initalized to ‘nofollow’

The function must return an Array of $attributes => $value.

Arguments:

$attrs: Array of $attribute => $value. $value can be a string or an Array. If $value is an array, all items of the array will be concatenated into a string, separated by a space.

$args: Array. Provides contextual information regarding the current heading. available offsets: ‘id’, ‘title’, ‘counter’, ‘depth’.

add_filter('joli_toc_item_link_attributes', 'add_toc_link_attributes', 10, 2);

function add_toc_link_attributes($attrs, $args) {
    //exemple of custom data attribute using a custom function
    $attrs['data-title-spanish'] =  translate_to_spanish($args['title']);
    $attrs['style'] = ['color: red;', 'text-shadow: 0 0 2px #00000080;'];
	
    return $attrs;
}

In the below example, we will add the rel=”nofollow” attribute to only specific posts (the option must be deactivated in this case):

add_filter('joli_toc_item_link_attributes', 'add_toc_link_attributes', 10, 2);

function add_toc_link_attributes($attrs, $args)
{
    global $post;

    $selected_posts = [123, 124, 125];

    //Adds nofollow attribute only to specific posts
    if (in_array($post->ID, $selected_posts)) {
        $attrs['rel'] =  'nofollow';
    }

    return $attrs;
}

Was this page helpful?