问题描述:

I have a Book Now button on each page of my website. I would like to know which button is selected and don't really want to add 25+ blocks to the site to add the class manually. I can use Google Analytics if I can make the button unique (add an additional class based on the page URL). But I'm not a coder although I'm familiar with both PHP and jQuery.

网友答案:

Hye Michael, after reading your question i have tested your scenario on my local test drupal site. And it's really easy to achieve it. Here is a piece of PHP code you need to put into your block you created.

<?php
$url = current_path();
$class_from_url = explode("/", $url);
echo "<a href=[link_to_whatever] class='". $class_from_url[0] ."'>[Link Title]</a>";
?>

Make sure your "PHP filter" module is enabled which will allow you to select PHP code from "Text formats" under the block body.

网友答案:

For Drupal 7, the best way to accomplish your goal would be to copy the theme_button() function to your theme's template.php file and add some custom code to check the URL and add the class.

YOURTHEME_button($vars) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element ['#attributes']['class'][] = 'form-' . $element ['#button_type'];
  if (!empty($element ['#attributes']['disabled'])) {
    $element ['#attributes']['class'][] = 'form-button-disabled';
  }

  // Check URL to determine what button class to add
  $button_class = null;
  $current_path = base_path() . request_path();
  switch ($current_path) {
    '/form1':
      $button_class = 'button-for-form1';
      break;
    '/form2':
      $button_class = 'button-for-form2';
      break;
  }
  if ($button_class !== null) {
    $element ['#attributes']['class'][] = $button_class;
  }

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

Note that this method will add the class only for URLs that you explicitly specify, and it ignores any user-supplied parameters that might be included as part of the URL.

相关阅读:
Top