1

For Node I already used https://www.drupal.org/project/metatag

For my custom module's detail page would like to add Open Graph tags for FB share.

So in my_test.module

function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Above one suppose to work but NOT WORKING.

function MY_MODULE_page_attachments_alter(array &$page) {

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => '',
        ],
      ];


  $page['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Above one is working, But I'm not able to get Page Variables. How will I get $variables in above function?

This one called in all pages of module, but I want to call only on detail page as mentioned in proprocess function

1

Got the solution

So in my_test.module

function template_preprocess_my_detail_page(&$variables) {

  $items = $variables['item'];

  $title =  $items->title;

  $og_title = [
        '#tag' => 'meta',
        '#attributes' => [
          'property' => 'og:title',
          'content' => $title,
        ],
      ];

  $variables['#attached']['html_head'][] = [$og_title, 'og_title'];
}

Change from

$variables['page']['#attached']['html_head'][] = [$og_title, 'og_title'];

to

$variables['#attached']['html_head'][] = [$og_title, 'og_title'];
0

I think that you need this.

    /**
 * Alter the metatags for pages that are not of content entities.
 *
 * @param array $metatags
 *   The special metatags to be added to the page.
 * @param array $context
 *   The context, containing the entity used for token replacements.
 */
function hook_metatags_alter(array &$metatags, array $context) {
  // Exclude metatags on frontpage.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $metatags = NULL;
  }
}
  • I need to get current post details as well. Can i get that then on basis of that need to set meta tags – Julia Mar 20 '18 at 1:42
  • Julia what kind of page do you have? – lamp5 Mar 20 '18 at 8:25
  • We are getting data from API & on basis of URL Say <domain.com>/test/111 will get Id & get data from API – Julia Mar 20 '18 at 9:27

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.