How can I add custom classes to node links in Drupal 8?
I want to add some classes to the Read more and Add new comment links in article teasers.
In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:
/**
* Implements hook_preprocess_links().
*/
function bartik_preprocess_links(&$variables) {
if (isset($variables['links']['node-readmore'])) {
$variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
}
if (isset($variables['links']['comment-add'])) {
$variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
}
}
Update:
Code above will add css class to any readmore link, to add for article only you can add preprocess and check type is article.
/**
* Implements hook_preprocess_HOOK() for node.html.twig.
*/
function bartik_preprocess_node(&$variables) {
...
if ($variables['teaser'] && $variables['node']->getType() == 'article') {
$node_type_is_article = &drupal_static('node_type_is_article');
$node_type_is_article = TRUE;
}
}
/**
* Implements hook_preprocess_links().
*/
function bartik_preprocess_links(&$variables) {
if ($node_type_is_article = &drupal_static('node_type_is_article')) {
if (isset($variables['links']['node-readmore'])) {
$variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
}
if (isset($variables['links']['comment-add'])) {
$variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
}
}
}
Clear all cache and see result. Here is my result: