4

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.

6

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:

enter image description here

4
  • OP referred only to article teasers. This will ad it to all content. Mar 16 '16 at 11:34
  • Hi J. Reynolds, i just update code to add css for node type article only, please check is it ok.
    – flashvnn
    Mar 16 '16 at 14:37
  • Bravo, grateful. Mar 16 '16 at 16:17
  • 1
    Would this not cause issues for when there are multiple nodes being displayed on a page? You're setting a boolean value into the statics, but that'll apply for every node that gets preprocessed. Aug 29 '18 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.